字符串和格式化输入输出(查漏补缺详细版)---永远不要认为你很牛,随便一个知识点就可以难倒你(一)

2014-11-24 08:13:42 · 作者: · 浏览: 1
1.strlen()函数和sizeof运算符
代码举例:
[cpp]
#include
#include /* provides strlen() prototype */
#define PRAISE "What a super marvelousname!"
int main(void)
{
char name[40];
printf("What's your name \n");
scanf("%s", name);
printf("Hello, %s. %s\n", name, PRAISE);
printf("Your name of %d letters occupies %d memory cells.\n",
strlen(name), sizeof name);
printf("The phrase of praise has %d letters ",
strlen(PRAISE));
printf("and occupies %d memory cells.\n", sizeof PRAISE);
return 0;
}
交互信息如下:
What's your name
Morgan Buttercup
Hello, Morgan. What a super marvelous name!
Your name of 6 letters occupies 40 memorycells.
The phrase of praise has 28 letters andoccupies 29 memory cells.
Press any key to continue
知识点:
sizeof运算符计算的是数据的大小,strlen()函数计算的是字符串的长度。
name的第七个单元存放空字符,它的存在告诉strlen()在哪里停止计数。
sizeof对于类型来说括号是必须的。对于具体量是可选的。如下使用
sizeof(char)
sizeof(float)
sizeof(6.22)
sizeof 6.22
sizeof name
2.常量和C预处理器
两种常量表示法:
#define PI 3.14
const float PI 3.14àC90新增的
limits.h中定义的一些常量如下:
符号常量
含义
CHAR_BIT
一个char的位数
CHAR_MAX
char类型的最大值
CHAR_MIN
char类型的最小值
SCHAR_MAX
signed char类型的最大值
SCHAR_MIN
signed char类型的最小值
UCHAR_MAX
unsigned char类型的最大值
SHRT_MAX
short类型的最大值
SHRT_MIN
short的最小值
USHRT_MAX
short类型的最大值
INT_MAX
int类型的最大值
INT_MIN
int类型的最小值
UINT_MAX
unsigned int类型的最大值
LONG_MAX
long类型的最大值
LONG_MIN
long类型的最小值
ULONG_MAX
unsigned long类型的最大值
LLONG_MAX
llong类型的最大值
LLONG_MIN
llong类型的最小值
ULLONG_MAX
unsigned llong类型的最大值
float.h中定义的一些常量如下:
符号常量
含义
FLT_MANT_DIG
float类型的尾数位数
FLT_DIG
float类型的最少有效数字位数(十进制)
FLT_MIN_10_EXP
带有全部有效数字的float类型的负指数的最小值(以10为底)
FLT_MAX_10_EXP
float类型的正指数的最大值
FLT_MIN
保留全部精度的float类型正数的最小值
FLT_MAX
float类型正数的最大值
FLT_EPSILON
1.00比1.00大的最小的float类型值之间的差值
代码举例:
[cpp]
// defines.c -- uses defined constants fromlimit.h and float.
#include
#include // integer limits
#include // floating-point limits
int main(void)
{
printf("Some number limits for this system:\n");
printf("Biggest int: %d\n", INT_MAX);
printf("Smallest long long: %lld\n", LLONG_MIN);
printf("One byte = %d bits on this system.\n", CHAR_BIT);
printf("Largest double: %e\n", DBL_MAX);
printf("Smallest normal float: %e\n", FLT_MIN);
printf("float precision = %d digits\n", FLT_DIG);
printf("float epsilon = %e\n", FLT_EPSILON);
getchar();
return 0;
}
输出结果如下:
Some number limits for this system:
Biggest int: 2147483647
Smallest long long: -9223372036854775808
One byte = 8 bits on this system.
Largest double: 1.797693e+308
Smallest normal float: 1.175494e-038
float precision = 6 digits
float epsilon = 1.192093e-007
3.printf()和scanf()函数
首先看几个知识点:
http://blog.csdn.net/wang6279026/article/details/8567828
代码示例:
[cpp]
// floats.c -- some floating-pointcombinations
#include
int main(void)
{
const double RENT = 3852.99; //const-style constant
printf("*%f*\n", RENT);
printf("*%e*\n", RENT);
printf("*%4.2f*\n", RENT);