1.通过试验(即编写带有此类问题的程序)观察系统如何处理整数上溢、浮点数上溢和浮点数下溢的情况。
#include <stdio.h> int main(void){ int biggest = 2147483647;//int最大值为2的32次方 - 1。32位二进制数第一位是0表示符号,后面31个1 int overflow1 = biggest + 1;//整数溢出 float overflow = 3.40e+38 * 100.0f;//上溢 float underflow = -3.40e+38 * 100.0f;//下溢 printf("%d,\n%d,\n%f,\n%f,",biggest,overflow1,overflow,underflow); }
效果:
2147483647,
-2147483648,
inf,
-inf,
2.编写一个程序,要求提示输入一个ASCII码值(如,66),然后打印输入的字符。
#include <stdio.h> int main(){ printf("请输入一个ASCII码值:"); fflush(stdout); int ASCII_vaule; scanf("%d",&ASCII_vaule); printf("%c",ASCII_vaule); return 0; }
效果:
请输入一个ASCII码值:66
B
3.编写一个程序,发出一声警报,然后打印下面的文本: Startled by the sudden sound, Sally shouted, "By the Great Pumpkin, what was that!"
#include <stdio.h> int main(){ printf("\a\n"); printf("Startled by the sudden sound, Sally shouted,\n"); printf("\"By the Great Pumpkin, what was that!\""); return 0; }
效果:
Startled by the sudden sound, Sally shouted,
"By the Great Pumpkin, what was that!"
4.编写一个程序,读取一个浮点数,先打印成小数点形式,再打印成指数形式。然后,如果系统支持,再打印成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> int main(){ float value; scanf("%f",&value); printf("Enter a floating-point value: %.2f\n",value); printf("fixed-point notation: %f\n",value); printf("exponential notation: %e\n",value); printf("p notation: %#.2a",value); return 0; }
效果:输入64.25效果
Enter a floating-point value: 64.25
fixed-point notation: 64.250000
exponential notation: 6.425000e+01
p notation: 0x1.01p+6
5.一年大约有3.156000e+7秒。编写一个程序,提示用户输入年龄,然后显示该年龄对应的秒数。
#include <stdio.h> int main(){ printf("请输入你的年龄:\n"); fflush(stdout); int age; scanf("%d",&age); double age_s = age * 3.156e7; printf("你的年龄转换成的秒数:%lf s",age_s); return 0; }
效果
请输入你的年龄:
22
你的年龄转换成的秒数:694320000.000000 s
6.1个水分子的质量约为3.0×10−23克。1夸脱水大约是950克。编写一个程序,提示用户输入水的夸脱数,并显示水分子的数量。
#include <stdio.h> int main(){ printf("请输入水的夸脱数:\n"); fflush(stdout); int kt; scanf("%d",&kt); int g = kt * 950; double num = g / 3.0e-23; printf("水分子的数量为:%lf 个",num); }
效果:
请输入水的夸脱数:
1
水分子的数量为:31666666666666665598517248.000000 个
7.1英寸相当于2.54厘米。编写一个程序,提示用户输入身高(/英寸),然后以厘米为单位显示身高。
#include <stdio.h> int main(){ printf("请输入你的身高(英寸): \n"); fflush(stdout); double inch; scanf("%lf",&inch); double cm = inch * 2.54; printf("你的身高是: %.0lf cm",cm); return 0; }
效果:
请输入你的身高(英寸):
68.2
你的身高是: 173 cm
8.在美国的体积测量系统中,1品脱等于2杯,1杯等于8盎司,1盎司等于2大汤勺,1大汤勺等于3茶勺。编写一个程序,提示用户输入杯数,并以 品脱、盎司、汤勺、茶勺为单位显示等价容量。思考对于该程序,为何使用浮点类型比整数类型更合适?
int main(){ printf("请输入杯数: \n"); fflush(stdout); double pint,ounce,spoon,tea_spoon; double cup_num; scanf("%lf",&cup_num); printf("%.0lf cup_num = %.2lf pint\n %.0lf cup_num = %.0lf ounce\n " "%.0lf cup_num = %.0lf spoon\n %.0lf cup_num = %.0lf tea_spoon\n" ,cup_num,cup_num/2,cup_num,cup_num*8,cup_num,cup_num*8*12,cup_num,cup_num*8*12*3); return 0; }
效果:
请输入杯数:
9
9 cup_num = 4.50 pint
9 cup_num = 72 ounce
9 cup_num = 864 spoon
9 cup_num = 2592 tea_spoon