五、 运算号、表达式和语句
1.循环简介
/* shoesl.c -- 把鞋码转换成英寸 */
#include <stdio.h>
#define ADJUST 7.31 // 字符常量
int main(void)
{
const double SCALE = 0.333;// const 变量
double shoe, foot;
shoe = 9.0;
foot = SCALE * shoe + ADJUST;
printf("Shoe size (men's) foot length\n");
printf("%10.1f %15.2f inches\n", shoe, foot);
return 0;
}
//Shoe size (men's) foot length
// 9.0 10.31 inches
/* shoes2.c -- 计算多个不同鞋码对应的脚长 */
#include <stdio.h>
#define ADJUST 7.31 //字符常量
int main(void)
{
const double SCALE = 0.333; // const 变量
double shoe, foot;
printf("Shoe size (men's) foot length\n");
shoe = 3.0;
while (shoe < 18.5) /* while 循环开始 */
{ /* 块开始 */
foot = SCALE * shoe + ADJUST;
printf("%10.1f %15.2f inches\n", shoe, foot);
shoe = shoe + 1.0;
} /* 块结束 */
printf("If the shoe fits, wear it.\n");
return 0;
}
//Shoe size (men's) foot length
// 3.0 8.31 inches
// 4.0 8.64 inches
// 5.0 8.97 inches
// 6.0 9.31 inches
//...
// 16.0 12.64 inches
// 17.0 12.97 inches
// 18.0 13.30 inches
2.基本运算符
■=、+、-、*、/
2.1 赋值运算符: =
int ex;
int why;
int zee;
const int TWO = 2;
why = 42;
zee = why;
ex = TWO * (why + zee);
/* golf.c -- 高尔夫锦标赛记分卡 */
#include <stdio.h>
int main(void)
{
int jane, tarzan, cheeta;
cheeta = tarzan = jane = 68;
printf(" cheeta tarzan jane\n");
printf("First round score %4d %8d %8d\n", cheeta, tarzan, jane);
return 0;
}
// cheeta tarzan jane
//First round score 68 68 68
2.2 加法运算符: +
printf("%d, 4 + 20");
//而不能:
//4 + 20
2.3 减法运算符: -
takehome = 224.00 - 24.00;
2.4 符号运算符: -和+
//标明或改变一个值的代数符号
rock = -12; //使用的负号称为一元运算符
smokey = -rocky;
dozen = +12;
2.5 乘法运算符: *
/* square.c -- 计算1 ~20的平方 */
#include <stdio.h>
int main(void)
{
int num = 1;
while (num < 21)
{
printf("%4d %6d\n", num, num * num);
num = num +1;
}
return 0;
}
//打印数字1 ~ 20及其平方
■指数增长
/* wheat.c -- 指数增长 */
#include <stdio.h>
#define SQUARES 64 // 棋盘中的方格数
int main(void)
{
const double CROP = 2E16; // 世界小麦年产谷粒数
double current, total;
int count = 1;
printf("square grains total ");
printf("fraction of \n");
printf(" added grains ");
printf("world 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;
}
//square grains total fraction of
// added grains world total
// 1 1.00e+000 1.00e+000 5.00e-017
// 2 2.00e+000 3.00e+000 1.50e-016
// 3 4.00e+000 7.00e+000 3.50e-016
// 4 8.00e+000 1.50e+001 7.50e-016
// 5 1.60e+001 3.10e+001 1.55e-015
// 6 3.20e+001 6.30e+001 3.15e-015
// 7 6.40e+001 1.27e+002 6.35e-015
// 8 1.28e+002 2.55e+002 1.27e-014
// 9 2.56e+002 5.11e+002 2.55e-014
// 10 5.12e+002 1.02e+003 5.12e-014
//...
// 55 1.80e+016 3.60e+016 1.80e+000
//...
// 64 9.22e+018 1.84e+019 9.22e+002
//That's all.