如何在C语言中打印百分号(%)?

43

为什么这个程序没有打印出%符号?

#include <stdio.h>

main()
{
     printf("%");
     getch();
}

3
你是否阅读了文档?文档对百分号有什么说明? - user529758
这个问题可以很容易地通过谷歌回答。OP本来可以运用他的逻辑,即'//'是斜杠的字符常量,并应用它。printf也有一个手册页,不是吗? - TheBlueCat
1
也许你的意思是 '\\' 是代表 \ 的字符常量?而 / 的字符常量则是 '/' - This isn't my real name
4个回答

94

你的问题在于你必须作出改变:

printf("%"); 
printf("%%");

或者您可以使用ASCII码并写成:

printf("%c", 37);

:)


8
C语言不要求使用ASCII编码。printf("%c", 37);是不具备可移植性的。 - user529758
2
@H2CO3 是的,但我喜欢这个答案,因为他给了一个额外的技巧! - Grijesh Chauhan
@GrijeshChauhan,我并没有说我不喜欢这个答案,它是一个好的答案。我只是指出上述片段不具备可移植性。 - user529758
@H2CO3 嗯,我知道...我只是想告诉你,我可能会简单地发布 printf("%%"); 的答案,但不使用 ASCII。你在我编辑这个答案时在这里发表了评论。 :) - Grijesh Chauhan
1
@GrijeshChauhan 当然可以,不冒犯 :) - user529758
5
为什么不使用 '%' 而是用 37 - Diti

27
这篇文章中没有解释为什么要打印百分号。一个人必须键入%%,而不是例如转义字符与百分号-\%
来自comp.lang.c FAQ list · Question 12.6
引用: The reason it's tricky to print % signs with printf is that % is essentially printf's escape character. Whenever printf sees a %, it expects it to be followed by a character telling it what to do next. The two-character sequence %% is defined to print a single %. To understand why % can't work, remember that the backslash \ is the compiler's escape character, and controls how the compiler interprets source code characters at compile time. In this case, however, we want to control how printf interprets its format string at run-time. As far as the compiler is concerned, the escape sequence % is undefined, and probably results in a single % character. It would be unlikely for both the \ and the % to make it through to printf, even if printf were prepared to treat the \ specially.
因此,必须键入printf("%%");才能打印单个%的原因是在printf函数中定义了这样的内容。%是printf的转义字符,而\是编译器的转义字符。

感谢您提供原因。 - Dave Voyles

8
使用"%%"。该手册页面描述了这个要求:

% 写入一个'%'。不转换任何参数。完整的转换规范是'%%'。


3
尝试以这种方式打印
printf("%%");

4
这个答案可以更加有用。它没有给读者提供任何参考,使他们了解自己的错误。 - Diti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接