C Primer Plus随手笔记(随意记录,持续更新。)

shijianzhongdeMacBook-Pro:c_study shijianzhong$ gcc print1.c 
print1.c:10:19: warning: more '%' conversions than data arguments [-Wformat]
printf("%d minus %d is %d\n",ten);
                 ~^
1 warning generated.
shijianzhongdeMacBook-Pro:c_study shijianzhong$ ./a.out 
Doing it right: 10 minus 2 is 8
Doing it wrong: 10 minus 0 is 1582628912
shijianzhongdeMacBook-Pro:c_study shijianzhong$ ./a.out 
Doing it right: 10 minus 2 is 8
Doing it wrong: 10 minus 0 is -1165623103
shijianzhongdeMacBook-Pro:c_study shijianzhong$ cat print1.c 
#include<stdio.h>
int main(void)
{
int ten=10;
int two=2;

printf("Doing it right: ");
printf("%d minus %d is %d\n",ten,2,ten-two);
printf("Doing it wrong: ");
printf("%d minus %d is %d\n",ten);

return 0;
}
shijianzhongdeMacBook-Pro:c_study shijianzhong$ 

 上面写了一个printf函数里面的参数不定,如果%d格式化的数量与输入的参数不一样,我编译的时候会报警,但还是能够编译通过,不能改打印出的值是内存中的任意值。

所以使用printf()函数时,要确保转换说明的数量与待打印值的数量相等。

C中的8进制显示为前面带一个0,16进制为0x跟Python一样

如果想格式化输出的时候,通过0x或0的形式显示八进制与16进制,需要格式化的时候已%#o,%#x形式.

shijianzhongdeMacBook-Pro:c_study shijianzhong$ gcc bases.c 
shijianzhongdeMacBook-Pro:c_study shijianzhong$ ./a.out 
dec=100;octal=144;hex=64
dec=100;octal=0144;hex=0x64
shijianzhongdeMacBook-Pro:c_study shijianzhong$ cat bases.c 
/* bases.c--以十进制、八进制、十六进制打印十进制数100 */
# include<stdio.h>
int main(void)
{
int x = 100;

printf("dec=%d;octal=%o;hex=%x\n",x,x,x);
printf("dec=%d;octal=%#o;hex=%#x\n",x,x,x);

return 0;
}

shijianzhongdeMacBook-Pro:c_study shijianzhong$ 

其他整数类型

C语言提供了三个附属管子见修饰基本整数类型:short、long和unsigned

超过范围的显示

shijianzhongdeMacBook-Pro:c_study shijianzhong$ ./a.out 
2147483647 -2147483648 -2147483647 
4294967295 0 1 
shijianzhongdeMacBook-Pro:c_study shijianzhong$ cat toobig.c 
/* toobig.c-- 超出系统允许的最大int值*/
#include<stdio.h>
int main(void)
{
int i = 2147483647;
unsigned int j = 4294967295;

printf("%d %d %d \n",i,i+1,i+2);
printf("%u %u %u \n", j, j+1, j+2);

return 0;
}
shijianzhongdeMacBook-Pro:c_stu5ldy shijianzhong$ 

 溢出范围感觉跟循环一样,又重新开始了,跟汽车公里表有点像。

打印short、long、long long 和unsigned类型

另外都是首字母开头格式化,比如%ld  %lld %llu %u等

对于short类型,需要使用h前缀, %hd,十进制显示short类型数字,%ho八进制显示short类型的整数。

shijianzhongdeMacBook-Pro:c_study shijianzhong$ ./a.out 
un= 3000000000 and not -1294967296
end= 200 and 200
big= 65537 and not 1
verybig= 12345678908642 and not 12345678908642
shijianzhongdeMacBook-Pro:c_study shijianzhong$ cat print2.c 
/* print2.c-- 更多printf()的特性*/
#include<stdio.h>
int main(void)
{
unsigned int un = 3000000000;
short end = 200;
long big = 65537;
long long verybig = 12345678908642;

printf("un= %u and not %d\n", un, un);
printf("end= %hd and %d\n", end, end);
printf("big= %ld and not %hd\n", big, big);
printf("verybig= %lld and not %ld\n", verybig, verybig);

return 0;

}
shijianzhongdeMacBook-Pro:c_study shijianzhong$ 

 不同的格式化输出,针对的位数不同 %hd,针对的是16位,%ld针对的是32位。

编译器在编译的时候,如果型号不对,还是会报提醒的。

char类型。

猜你喜欢

转载自www.cnblogs.com/sidianok/p/12825028.html