while()循环、基本运算符、平方、指数增长、
1、while(条件)
{代码块}
示例程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include<stdio.h> #define ADJUST 7.64 #define SCALE 0.325 int main()
{ double shoe,foot;
printf ( "shoe size (men's) foot length\n" );
shoe=3.0; while (shoe<18.5)
{ foot=SCALE*shoe+ADJUST; printf ( "%10.2f %15.2f inches\n" ,shoe,foot);
shoe=shoe+1.0; } printf ( "if the shoe fits,wear it.\n" );
return 0;
} |
运行结果:
2、基本运算符:=(赋值运算符)、+、-、*、/,c木有指定指数运算符,但是提供了pow()函数,例如pow(3.5,2.2),返回值为3.5的2.2次幂。
实例程序:紧接着如上:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#include<stdio.h> #define ADJUST 7.64 #define SCALE 0.325 int main()
{ double shoe,foot;
int jane,tarzan,cheeta;
int num=1;
printf ( "shoe size (men's) foot length\n" );
shoe=3.0; while (shoe<18.5)
{ foot=SCALE*shoe+ADJUST; printf ( "%10.2f %15.2f inches\n" ,shoe,foot);
shoe=shoe+1.0; } printf ( "if the shoe fits,wear it.\n" );
/*三重赋值*/ cheeta=tarzan=jane=68; printf ( " cheeta tarzan jean\n" );
printf ( "first round score %4d %8d %8d\n" ,cheeta,tarzan,jane); //多种程序语言将在这里的三重赋值处卡壳,但是c可以顺利接受它,赋值是从右向左依次进行的,先是jane得到68,然后是Tarzan,cheeta.
/*加减法,他们被称为二元或者双值运算符,因为他们的运算需要两个操作数*/ printf ( "%d\n" ,4+20);
printf ( "%f\n" ,224.00-24.00);
//符号运算符:-和+,如rocky=-12;当这样使用-号时,称为一元运算符,表示他只需一个操作数。 /*c没有计算平方的函数,可以通过以下程序实现*/ while (num<21)
{ printf ( "%4d %6d\n" ,num,num*num);
num=num+1; } return 0;
} |
运行结果:
3、指数增长:
故事:有位强大的统治者想奖励一个做出巨大贡献的学者,学者指着棋盘说,在第一个方格里放一粒小麦,第二个放2粒,第三个放4粒,依次类推。
实例程序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
#include<stdio.h> #define SQUARES 64 #define CROP 1E15//以粒记得美国的小麦产量 int main()
{ double current,total;
int count=1;
printf ( "square grains total" );
printf ( "fraction of \n" );
printf ( " added grain " );
printf ( "US total\n" );
total=current=1.0; /*开始时是1粒*/
printf ( "%4d %13.2e %12.2e %12.2e\n" ,count,current,total,total/CROP);
while (count<SQUARES)
{
count=count+1;
current=2.0*current;
total=total+current;
printf ( "%4d %13.2e %12.2e %12.2e\n" ,count,current,total,total/CROP);
}
printf ( "that's all.\n" );
return 0;
}
|
运行程序:
这个例子演示了指数增长的现象。世界人口的增长和我们对能源的使用都遵循同样的模式。
本文转自 lillian_trip 51CTO博客,原文链接:http://blog.51cto.com/xiaoqiaoya/1951911,如需转载请自行联系原作者