3.11 编程练习
- 通过试验(即编写带有此类问题的程序)观察系统如何处理整数上溢、浮点数上溢和浮点数下溢的情况。
#include<stdio.h>
#include<stdlib.h>
int main(){
int a=2147483647;
float b=3.4e38*100.0f;
float c=(3.4e-38)/(100.0e100);
printf("%d %d %d\n",a,a+1,a+2);
printf("%e\n",b);
printf("%e\n",c);
return 0;
}
输出:
2147483647 -2147483648 -2147483647
1.#INF00e+000\n
0.000000e+000
对于整数,小于最小值为下溢,大于最大值为上溢(指代数值)。
对于浮点数,绝对值大于浮点数所能表示的最大范围,为上溢,当作INF(指绝对值);绝对值小于浮点数所能表达的最小值,为下溢,当作0;
- 编写一个程序,要求提示输入一个ASCII码值(如,66),然后打印输入的字符。
#include<stdio.h>
#include<stdlib.h>
int main(){
int i;
printf("请输入一个ASCII值:");
scanf("%d",&i);
printf("ASCII值对应的字符为:%c\n",i);
return 0;
}
- 编写一个程序,发出一声警报,然后打印下面的文本:
Startled by the sudden sound, Sally shouted,
“By the Great Pumpkin, what was that!”
#include<stdio.h>
#include<stdlib.h>
int main(){
printf("\a Started by the sudden sound, Sally shouted,\n\"By the Great Pumpkin, what was that!\"");
return 0;
}
- 编写一个程序,读取一个浮点数,先打印成小数点形式,再打印成指数形式。然后,如果系统支持,再打印成p记数法(即十六进制记数法)。按以下格式输出(实际显示的指数位数因系统而异):
Enter a floating-point value: 64.25
fixed-point notation: 64.250000
exponential notation: 6.425000e+01
p notation: 0x1.01p+6
#include<stdio.h>
#include<stdlib.h>
int main(){
float i;
printf("Enter a floating-point value:");
scanf("%f",&i);
printf("fixed-point notation: %f\n",i);
printf("exponential notation: %e\n",i);
printf("p notation: %a",i);
return 0;
}
- 一年大约有3.156×107秒。编写一个程序,提示用户输入年龄,然后显示该年龄对应的秒数。
#include<stdio.h>
#include<stdlib.h>
int main(){
int year=0;
float ageminutes;
printf("请输入你的年龄:");
scanf("%d",&year);
ageminutes=year*3.156e7;
printf("年龄对应的秒数为:%.2f",ageminutes);
printf("年龄对应的秒数为:%e",ageminutes);
return 0;
}
- 1个水分子的质量约为3.0×10−23克。1夸脱水大约是950克。编写一个程序,提示用户输入水的夸脱数,并显示水分子的数量。
#include<stdio.h>
#include<stdlib.h>
int main(){
float quantity_mol=3.0e-23;
float quantity_qt=950;
float quarts;
float molecules;
printf("请输入水的夸克数:");
scanf("%f",&quarts);
molecules=quarts*quantity_qt/quantity_mol;
printf("水分子的数量: %e",molecules);
return 0;
}
- 1英寸相当于2.54厘米。编写一个程序,提示用户输入身高(/英寸),然后以厘米为单位显示身高。
#include<stdio.h>
#include<stdlib.h>
int main(){
float inch;
float cm;
printf("输入身高:(/英尺)");
scanf("%f",&inch);
cm=inch*2.54;
printf("身高为 %.2f厘米",cm );
return 0;
}
- 在美国的体积测量系统中,1品脱等于2杯,1杯等于8盎司,1盎司等于2大汤勺,1大汤勺等于3茶勺。编写一个程序,提示用户输入杯数,并以品脱、盎司、汤勺、茶勺为单位显示等价容量。思考对于该程序,为何使用浮点类型比整数类型更合适?
#include<stdio.h>
#include<stdlib.h>
int main(){
float cup;
printf("请输入杯数:");
scanf("%f",&cup);
float pints=cup/2;
float ounces=cup*8;
float spoons=cup*8*2;
float teaspoons=cup*8*3;
printf("品脱: %f \t盎司: %f \t汤勺: %f \t茶勺: %f\n",pints,ounces,spoons,teaspoons);
return 0;
}