C语言 为什么 %d 代表整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13409014/
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
why does %d stand for Integer?
提问by grasingerm
I know this doesn't sound productive, but I'm looking for a way to remember all of the formatting codes for printfcalls. %s, %p, %fare all obvious, but I can't understand where %dcomes from. Is %ialready taken by something else?
我知道这听起来效率不高,但我正在寻找一种方法来记住printf呼叫的所有格式代码。%s, %p,%f都是显而易见的,但我不明白%d从哪里来。是不是%i已经被别的东西拿走了?
回答by Brian Campbell
It stands for "decimal" (base 10), not "integer." You can use %xto print in hexadecimal(base 16), and %oto print in octal(base 8). An integer could be in any of these bases.
它代表“十进制”(基数为 10),而不是“整数”。您可以使用%x以十六进制(基数 16)%o打印和以八进制(基数 8)打印。整数可以是这些基数中的任何一个。
In printf(), you can use %ias a synonym for %d, if you prefer to indicate "integer" instead of "decimal," but %dis generally preferred as it's more specific.
在中,如果您更喜欢表示“整数”而不是“十进制”,则printf()可以将%i用作 的同义词%d,但%d通常更受欢迎,因为它更具体。
On input, using scanf(), you can use use both %iand %das well. %imeans parse it as an integer in any base (octal, hexadecimal, or decimal, as indicated by a 0or 0xprefix), while %dmeans parse it as a decimal integer.
在输入时,使用scanf(),您可以同时使用%i和%d。%i表示将其解析为任何基数的整数(八进制、十六进制或十进制,如 a0或0x前缀所示),而%d表示将其解析为十进制整数。
Here's an example of all of them in action:
以下是所有这些操作的示例:
#include <stdio.h>
int main() {
int out = 10;
int in[4];
printf("%d %i %x %o\n", out, out, out, out);
sscanf("010 010 010 010", "%d %i %x %o", &in[0], &in[1], &in[2], &in[3]);
printf("%d %d %d %d\n", in[0], in[1], in[2], in[3]);
sscanf("0x10 10 010", "%i %i %i", &in[0], &in[1], &in[2]);
printf("%d %d %d\n", in[0], in[1], in[2]);
return 0;
}
So, you should only use %iif you want the input base to depend on the prefix; if the input base should be fixed, you should use %d, %x, or %o. In particular, the fact that a leading 0puts you in octal mode can catch you up.
因此,只有%i在希望输入基数依赖于前缀时才应使用;如果输入的基础应该是固定的,你应该使用%d,%x或%o。特别是,领先0让您进入八进制模式这一事实可以赶上您。
回答by Juan Mendes
http://en.wikipedia.org/wiki/Printf_format_stringseems to say that it's for decimal as I had guessed
http://en.wikipedia.org/wiki/Printf_format_string似乎说它是十进制的,正如我所猜测的
d,i
d,i
int as a signed decimal number. '%d' and '%i' are synonymous for output, but are different when used with scanf() for input (using %i will interpret a number as hexadecimal if it's preceded by 0x, and octal if it's preceded by 0.)
int 作为有符号的十进制数。'%d' 和 '%i' 是输出的同义词,但是在与 scanf() 一起用于输入时是不同的(如果前面是 0x,则使用 %i 会将数字解释为十六进制,如果前面是 0,则将其解释为八进制。)

