《C Primer Plus》第3章 复习题与编程练习
复习题
1~10
11. 指出下列转义序列的含义
- \n:回车字符
- \\:\
- \“:”
- \t:水平制表符
编程练习
1. 溢出测试
无符号整型溢出:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// unsigned char占2字节,取值范围为:0~256
unsigned char a = 256 + 1;
printf("%d\n", a); //输入1
system("pause");
return 0;
}
对于无符号整型上溢,对28*sizeof(type)做模运算。
有符号整型溢出:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
// signed char占2字节,取值范围为:-128~127
signed char a = -129;
signed char b = 128;
printf("%d\n", a); //下溢,输入127
printf("%d\n", b); // 上溢,输出-128
system("pause");
return 0;
}
可以将取值范围是为一个循环数组,超过127后,回到-128;同理,低于-128后,回到127。
浮点数溢出:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
float toobig = 3.4e38 * 100.0f;
float tosmall = 0.1234e-45;
printf("%f\n", toobig); //上溢,输出1.#INF00
printf("%e\n", tosmall); //下溢,输出0.000000e+000
system("pause");
return 0;
}
可以看到,上溢输出INF特殊字符,下溢丢失精度,输出0。
2. 输入ASCII值,打印对应字符
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char c;
printf("Please input a number: ");
scanf("%d", &c);
printf("%d in ASCII is %c.\n", c, c);
system("pause");
return 0;
}
测试:
3. 打印
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
printf("\aStartled by the sudden sound, Sally shouted,\n\"By the Great Pumpkin, what was that!\"\n");
system("pause");
return 0;
}
4. 浮点数打印
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
float num;
printf("Enter a floating-point value: ");
scanf("%f", &num);
printf("fixed-point natation: %.6f\n", num);
printf("exponential notation: %.6e\n", num);
printf("p notation: %.2a\n", num);
system("pause");
return 0;
}
5. 输入年龄,打印对应秒数
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int age;
printf("please input your age: ");
scanf("%d", &age);
printf("You've been alive for %f seconds.\n", age * 3.156e7);
system("pause");
return 0;
}
6. 输入水的夸脱数,打印水分子数
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int quart;
printf("please input the quart: ");
scanf("%d", &quart);
printf("%d quarts of water has %e water molecules.\n", quart, quart * 950 / (3.0e-23));
system("pause");
return 0;
}
7. 输入身高(英寸),打印身高(厘米)
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int height;
printf("Please input your height(inch): ");
scanf("%d", &height);
printf("%d inchs is equaled to %f cm.\n", height, height * 2.54);
system("pause");
return 0;
}
8. 打印等价容量
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
float glass;
float pint;
float ounce;
float spoon;
float teaspoon;
printf("How many glasses?\n");
scanf("%f", &glass);
pint = glass / 2;
ounce = 8 * glass;
spoon = 2 * ounce;
teaspoon = 3 * spoon;
printf("%f glasses=%f pints, =%f ounces, =%f spoons, =%f teaspoons\n", glass, pint, ounce, spoon, teaspoon);
system("pause");
return 0;
}