这个程序读入一系列每日的最低温度(摄氏度),并报告输入的总数,以及最低温度在零度如下的天数的百分率。在一个循环里使用scanf()读入数值,在每一次循环中增长计数器的值来统计输入数值的个数。if语句检测低于零度如下的温度并单独统计这些天的数目。express
程序清单7.1 colddays.cui
------------------------------------code
//colddays.c --求出温度低于零度的天数的百分率 #include <stdio.h> int main (void) { const int FREEZING = 0; float temperature; int cold_days = 0; int all_days = 0; printf("Enter the list of daily low temperatures.\n"); printf("Use Celsius,and enter q to quit.\n"); while(scanf("%f",&temperature)==1) { all_days++; if(temperature<FREEZING) cold_days++; } if(all_days!=0) printf("%d days total:%.1f%% were below freezing.\n", all_days,100.0*(float)cold_days / all_days); if(all_days==0) printf("No data entered!\n"); return 0; } /*下面是一个运行示例: Enter the list of daily low temperatures. Use Celsius,and enter q to quit. 12 5 -2.5 0 6 8 -3 -10 5 10 q 10 days total:30.0% were below freezing. */
用float而不是int来声明temperature,这样程序就既能接受像8那样的输入,也能接受像-2.5这样的输入。编译器
为了不整数除法,示例程序在计算百分率时使用了类型转换float。使用类型转换能够代表意图,并保护程序免受不完善编译器的影响。it
if语句被称为分支语句(branching statement)或选择语句(selection statement),由于它提供了一个交汇点,在此处程序选择两条分支中的一条前进。通常形式以下:io
if(expression)编译
statementclass
若是expression为真,就执行statement;不然跳过该语句。和while语句的区别在于在if中,判断和执行只有一次,而在while循环中,判断和执行能够重复屡次。object
注意,即便if中使用了一个复合语句,整个if结构仍将被看做一个简单的语句。select