字符串和格式化输入输出(查漏补缺详细版)---永远不要认为你很牛,随便一个知识点就可以难倒你(二)
printf("*%3.1f*\n", RENT);
printf("*%10.3f*\n", RENT);
printf("*%10.3e*\n", RENT);
printf("*%+4.2f*\n", RENT);
printf("*%010.2f*\n", RENT);
return 0;
}
输出结果:
*3852.990000*
*3.852990e+003*
*3852.99*
*3853.0*
* 3852.990*
*3.853e+003*
*+3852.99*
*0003852.99*
Press any key to continue
代码讲解:0标志使之产生前导零。
代码示例:
[cpp]
/* flags.c -- illustrates some formattingflags */
#include
int main(void)
{
printf("%x %X %#x\n", 31, 31, 31);
printf("**%d**% d**% d**\n", 42, 42, -42);
printf("**%5d**%5.3d**%05d**%05.3d**\n", 6, 6, 6, 6);
return 0;
}
输出结果:
1f 1F 0x1f
**42** 42**-42**
** 6** 006**00006** 006**
Press any key to continue
代码讲解:主要是讲解空格的使用,说明符中,在正值之前产生一个前导空格,在负值之前不产生前导空格,这样会使有效位相同的正值和负值以相同字段打印输出。第三个输出语句主要说明了,0与.同时出现的时候,0标志将被忽略。
代码示例:
[cpp]
/* strings.c -- string formatting */
#include
#define BLURB "Authenticimitation!"
int main(void)
{
printf("/%2s/\n", BLURB);
printf("/%24s/\n", BLURB);
printf("/%24.5s/\n", BLURB);
printf("/%-24.5s/\n", BLURB);
return 0;
}
输出结果:
/Authentic imitation!/
/ Authentic imitation!/
/ Authe/
/Authe /
Press any key to continue
代码讲解:【.5】告诉printf()函数只打印五个字符。
4.重点:printf()函数格式化输出之不匹配输出【补充,原文链接:http://blog.csdn.net/wang6279026/article/details/8545706】
代码示例:
[cpp]
/* floatcnv.c -- mismatched floating-pointconversions */
#include
int main(void)
{
float n1 = 3.0;
double n2 = 3.0;
long n3 = 2000000000;
long n4 = 1234567890;
printf("%.1e %.1e %.1e %.1e\n", n1, n2, n3, n4);
printf("%ld %ld\n", n3, n4);
printf("%ld %ld %ld %ld\n", n1, n2, n3, n4);
getchar();
return0;
}
输出结果【VC】:
3.0e+000 3.0e+000 3.1e+046 0.0e+000
2000000000 1234567890
0 1074266112 0 1074266112
Press any key to continue
输出结果【DEV】:
3.0e+000 3.0e+000 3.1e+046 2.8e-306
2000000000 1234567890
0 1074266112 0 1074266112
代码讲解:
主要说明第二个输出语句和第三个输出语句,printf("%ld %ld %ld %ld\n", n1, n2, n3, n4);该调用告诉计算机把四个变量的值传递给计算机,计算机把他们放置到堆栈的一块内存区域中进行管理。计算机根据变量的类型而不是转换说明符把这些值放入到堆栈中。所以,分别占用字节为8(float被转换为了double),8,4,4。然而%d说明符,说明了要取出的字节数是4.所以按照顺序取出来就会出错。因此第二个输出语句正确,第三个确有问题【当你明白了printf()的运行机制以后,你会更加了解他的方式】
5.打印较长的字符串【三种方式】
[cpp]
printf("Hello, young lovers, whereveryou are.");
printf("Hello, young" " lovers," " wherever you are.");
printf("Hello, young lovers"
",wherever you are.");
代码示例:
[cpp]
/* longstrg.c -- printing long strings */
#include
int main(void)
{
printf("Here's one way to print a ");
printf("long string.\n");
printf("Here's another way to print a \
long string.\n");
printf("Here's the newest way to print a "
"long string.\n"); /* ANSI C */
return 0;
}
输出结果:
Here's one way to print a long string.
Here's another way to print a long string.
Here's the newest way to print a longstring.
Press any key to continue
6.printf()和scanf()函数的*修饰符
知识讲解:
如果转换说明符是%*d,那么参数列表中应该包括一个*的值和一个d的值。该技术也可以和一起使用来指定精度和指定宽度。
代码示例:
[cpp]
/* varwid.c -- uses variable-width outputfield */
#include
int main(void)
{