我有以下代码:
double dtemp = (some value)
printf("\n***Hand washing: cost per kg/item: %.2f, cost: %.2f.\n", 5, dtemp);
Run Code Online (Sandbox Code Playgroud)
打印出来:
***洗手:每公斤/项目的成本:0.00,成本:0.00.
当我将常量5更改为保持5的双变量时,它会打印(根据输入):
***洗手:每公斤/件的成本:5.00,成本:20.00.
为什么常数5会影响dtemp的评估?我正在使用gcc 4.6.2(MinGW)并在TCC中测试它.
f转换说明符需要double在与printf函数一起使用时才传递int.传递一个int未定义的行为,这意味着任何事情都可能发生.
我的编译器(gcc 4.4.3)警告消息解释了这一点:
format ‘%.2f’ expects type ‘double’, but argument 2 has type ‘int’
Run Code Online (Sandbox Code Playgroud)
由于您在格式字符串中传递的值(int)不同于指定的(double),因此由于此不匹配而导致行为未定义
正如您所观察到的,一旦您将其调整为一致,您将获得您期望的输出.也就是说,
/* provide a double value */
printf("\n***Hand washing: cost per kg/item: %.2f, cost: %.2f.\n", 5.0, dtemp);
Run Code Online (Sandbox Code Playgroud)
输出:
***Hand washing: cost per kg/item: 5.00, cost: 3.14.
Run Code Online (Sandbox Code Playgroud)
要么
/* specify an integer value in the format string */
printf("\n***Hand washing: cost per kg/item: %d, cost: %.2f.\n", 5, dtemp);
Run Code Online (Sandbox Code Playgroud)
输出:
***Hand washing: cost per kg/item: 5, cost: 3.14.
Run Code Online (Sandbox Code Playgroud)
始终是一个好主意,在编译器上提高警告级别,然后跟进所有警告,并对可以忽略的内容和不可忽略的内容做出深思熟虑的决定.