c - 带有 "%d"以 0 开头的数字(例如 "0102")的 printf 给出意外的答案(例如 '"66")

标签 c hex printf octal

我在 printf 语句中使用了以下代码。

void main()
{
    int n=0102;
    printf("%d", n);
}

这将打印 66 作为答案。我还将变量 n 的值更改为 012。它给出了答案 10。请帮助我了解此转换是如何完成的???

最佳答案

这是因为当数字(整数常量)的第一位是 0(第二位不能是 xX) ,编译器将其解释为八进制数。用 %d 打印它会给你一个十进制值。
要打印八进制值,您应该使用 %o 说明符

   printf("%o", n);  

6.4.4.1 整型常量:

  1. An integer constant begins with a digit, but has no period or exponent part. It may have a prefix that specifies its base and a suffix that specifies its type.

  2. A decimal constant begins with a nonzero digit and consists of a sequence of decimal digits. An octal constant consists of the prefix 0 optionally followed by a sequence of the digits 0 through 7 only. A hexadecimal constant consists of the prefix 0x or 0X followed by a sequence of the decimal digits and the letters a (or A) through f (or F) with values 10 through 15 respectively.


整数常量:

1.十进制常量:必须0开头。

 12  125  3546  

2.八进制常数:必须以0开头。

 012 0125 03546  

3.十六进制常量:总是以0x0X开头。

 0xf 0xff 0X5fff   

关于c - 带有 "%d"以 0 开头的数字(例如 "0102")的 printf 给出意外的答案(例如 '"66"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19652583/

相关文章:

c - 多线程编程中的exit命令是完全退出吗?

c - 如何使用c程序运行exe

c - 如何回到父进程......?

通过标记连接创建包含通用字符名称的标识符

batch-file - 这个批处理文件到底应该做什么?

java - 带文本的二维数组的打印格式

java - 如何将一个字符串中的一个字符与另一个字符串进行比较

C# 将大于 Int64 的数字转换为 HexaDecimal

c - 为什么 printf 语句不继续下一行?

c++ - Printf 和 C++ 字符串