C语言 如何在c中打印百分号(%)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17774821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I print the percent sign(%) in c
提问by Paul Filch
I am a beginner in C, and I was wondering why this program does not print % sign?
我是 C 的初学者,我想知道为什么这个程序不打印 % 符号?
The code is:
代码是:
#include<stdio.h>
main()
{
printf("%");
getch();
}
回答by C_Intermediate_Learner
Your problem is that you have to change:
你的问题是你必须改变:
printf("%");
to
到
printf("%%");
Or you could use ASCII code and write:
或者您可以使用 ASCII 代码并编写:
printf("%c", 37);
:)
:)
回答by macfij
there's no explanation in this topic why to print a percentage sign one must type %%and not for example escape character with percentage - \%.
from comp.lang.c FAQ list · Question 12.6:
本主题中没有解释为什么要打印必须键入的百分比符号,%%而不是例如带有百分比的转义字符 - \%。
来自comp.lang.c 常见问题列表·问题 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 看到 % 时,它都希望它后面跟着一个字符,告诉它下一步要做什么。两个字符的序列 %% 被定义为打印单个 %。
要理解为什么 \% 不能工作,请记住反斜杠 \ 是编译器的转义字符,它控制编译器在编译时解释源代码字符的方式。然而,在这种情况下,我们希望控制 printf 在运行时解释其格式字符串的方式。就编译器而言,转义序列 \% 未定义,可能会导致单个 % 字符。\ 和 % 都不太可能到达 printf,即使 printf 准备特别对待 \。
so the reason why one must type printf("%%");to print single % is that's what is defined in printf function. % is an escape character of printf's, and \ of compiler.
所以必须键入printf("%%");以打印单个 % 的原因是 printf 函数中定义的内容。% 是 printf 的转义字符,和编译器的 \。
回答by Carl Norum
回答by Santhosh Pai
Try printing out this way
尝试以这种方式打印出来
printf("%%");

