1.通过试验(即编写带有此类问题的程序)观察系统如何处理整数上溢、浮点数上溢和浮点数下溢的情况。
/*
int类型(整数类型)占用4字节,范围为-2^ 31 ~ 2^31-1;
即-2147483648 ~ 2147483647,
十六进制表示:0x80000000 ~ 0x7FFFFFFF。
float类型(单精度浮点数类型)占用4字节,
数值范围为 -3.4E+38 到 3.4E+38
*/
#include<stdio.h>
int main()
{
int a = 2147483647;
float b = 3.4e38 * 100.0f;
float c = (-3.4e-38 - 10) / 10e100;
printf("%zd", sizeof(int));
printf("%zd", sizeof(float));
printf("%d, %d, %d\n", a, a + 1, a + 2); //整数上溢
printf("%e\n", b); //浮点数上溢
printf("%e\n", c); //浮点数下溢
return 0;
}
2.编写一个程序,要求提示输入一个ASCII码值(如,66),然后打印输入的字符。
/*
输入ASCII码(如,66),打印输出字符
*/
#include<stdio.h>
int main()
{
int ascii;
printf("请输入一个ASCII码值:");
scanf("%d", &ascii);
printf("ASCII值:%d 的字符为:%c", ascii, ascii);
return 0;
}
3.编写一个程序,发出一声警报,然后打印下面的文本:
Startled by the sudden sound, Sally shouted,
"By the Great Pumpkin, what was that!"
/*
发出警报
打印
Startled by the sudden sound, Sally shouted,
"By the Great Pumpkin, what was that!"
*/
#include<stdio.h>
int main()
{
printf("\a");
printf("Startled by the sudden sound, Sally shouted,\n");
printf("\"By the Great Pumpkin, what was that!\"\n");
return 0;
}
4.编写一个程序,读取一个浮点数,先打印成小数点形式,再打印成指数形式。然后,如果系统支持,再打印成p记数法(即十六进制记数法)。按以下格式输出(实际显示的指数位数因系统而异):
Enter a floating-point value: 64.25
fixed-point notation: 64.250000
exponential notation: 6.425000e+01
p notation: 0x1.01p+6
/*
读取浮点数;
打印小数点形式;
打印指数形式;
打印p计数法;
*/
#include<stdio.h>
int main()
{
float f;
printf("Enter a floating-point value:");
scanf("%f", &f);
printf("fixed-point notation: %.6f\n", f);
printf("exponential notation: %.6e\n", f);
printf("p notation: %.2a\n", f);
return 0;
}
5.一年大约有3.156×107 秒。编写一个程序,提示用户输入年龄,然后显示该年龄对应的秒数。
/*
提示输入年龄;
读取年龄;
计算年龄对应秒数;
打印秒数;
*/
#include<stdio.h>
int main()
{
int years, seconds;
const int s = 3.156e7; //一年的秒数
printf("请输入您的年龄:");
scanf("%d", &years);
seconds = s * years;
printf("您已经活了 %d 秒", seconds);
return 0;
}
6.1个水分子的质量约为3.0×10−23 克。1夸脱水大约是950克。编写一个程序,提示用户输入水的夸脱数,并显示水分子的数量。
提示输入水的夸脱数;
计算水分子数;
输出水分子数;
*/
#include <stdio.h>
int main() {
float a;
scanf("%f", &a);
a = (a * 950) / (3.0 * 1e-23);
printf("%.6E", a);
return 0;
}