《C Primer Plus》学习笔记——数据和C

1、int类型

长度:4个字节;范围:-231 ~ (231 - 1);

提示1:用八进制显示整数用%0;用十六进制显示整数用%x;想显示C语言前缀,使用说明符%#o,%#x,%#X分别生成0、0x和0X前缀。

对应于16位单位,short类型和int类型的最小取值范围为-32768到32767;对应于32位单位,long类型的最小取值范围为-2147483648

到-2147483647;对于unsigned int类型和unsigned short类型,最小取值范围为0到65535;对于unsigned long类型,最小取值范围为0到

4294967295。

提示2:打印unsigned int数字,可以使用%u。打印long数值,可以使用%ld。

 

2、char类型

字符字节通常为8位。用%c打印一个字符

 

3、可移植的类型:inttype.h

 

4、float、double和long double类型

float:基本浮点类型。至少能精确表示6位有效数字。(6-7)位

double:至少能精确表示10位有效数字。(15-16)位

long double:(18-19)位

默认情况下,编译器将浮点常量当作double类型。可以使用f或F后缀使编译器把浮点常量当作float类型,L后缀使一个数字成为long double类型

 

5、使用数据类型

  • 在将浮点值转换为整数时,C简单地丢弃小数部分(截尾),而不进行四舍五入。
  • 使用%d显示float值不会把该float值转换为近似的int值,而是显示垃圾值。

 

6、编程练习

1、通过试验的方法(即编写带有此类问题的程序)观察系统如何处理整数上溢、浮点数上溢和浮点数下溢的情况。

 1 #include<stdio.h>
 2 
 3 int main(void)
 4 {
 5      unsigned int a=4294967295;
 6      float b=3.4E38;
 7      float c=b*10;
 8      float d=0.1234E-2;
 9      printf("%u+1=%u\n",a,a+1);
10      printf("%e*10=%e\n",b,c);
11      printf("%f/10=%f\n",d,d/10);
12      return(0);
13 }

2、编写一个程序,要求输入一个ASCII码值(如66),然后输出相应的字符。

1 #include<stdio.h>
2 
3 int main(void)
4 {
5      char a;
6      scanf("%d",&a);
7      printf("%c\n",a);
8      return(0);
9 }

3、编写一个程序,发出警报声,并打印下列文字:

    Startled by the sudden sound, Sally shouted, "By the Great Pumpkin,  what was that!"

1 #include<stdio.h>
2 
3 int main(void)
4 {
5    printf("\aStartled by the sudden sound,Sally shouted,\"By the Great pumpkin,what was that!\"\n");
6    return(0);
7 }

4、编写一个程序,读入一个浮点数,并分别以小数形式和指数形式打印。输出应如同下面格式(实际显示的指数位数也许因系统而不同):

    The input is 21.290000 or 2.129000e+001.

1 #include<stdio.h>
2 
3 int main(void)
4 {
5      float a;
6      scanf("%f",&a);
7      printf("The input is %f or %e\n",a,a);
8      return(0);
9 }

5、一年约有3.156×l0^7s。编写一个程序,要求输入您的年龄,然后显示该年龄合多少秒。

 1 #include<stdio.h>
 2 
 3 int main(void)
 4 {
 5      float a;
 6      printf("Please input your age:");
 7      scanf("%f",&a);
 8      printf("Your age is %e seconds\n",a*3.156E7);
 9      return(0);
10 }

6、1个水分子的质量约为3.0×10^-23g,1夸脱水大约有950g。编写一个程序,要求输入水的夸脱数,然后显示这么多水中包含多少个水分子。

 1 #include<stdio.h>
 2 
 3 int main(void)
 4 {
 5      float a;
 6      printf("Please input how much quarts the water is:");
 7      scanf("%f",&a);
 8      printf("%f quarts  water has %e molecules.\n",a,a*950/3E-23);
 9      return(0);
10 }

7、1英寸等于2.54cm。编写一个程序,要求输入您的身高(以英寸为单位),然后显示该身高值等于多少厘米。如果您愿意,也可以要求以厘米为单位输入身高,然后以英寸为单位进行显示。

 1 #include<stdio.h>
 2 
 3 int main(void)
 4 {
 5      float a;
 6      printf("Please input your height by inches:");
 7      scanf("%f",&a);
 8      printf("Your height is %fcm.\n",a*2.54);
 9      return(0);
10 }

 

posted @ 2014-04-17 11:29  cxyfreedom  阅读(277)  评论(0编辑  收藏  举报