互相影响的printf参数 [英] printf parameters affecting each other

查看:109
本文介绍了互相影响的printf参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

double dtemp = (some value)
printf("\n***Hand washing: cost per kg/item: %.2f, cost: %.2f.\n", 5, dtemp);

它打印出来:

***手洗:每千克/项目费用:0.00,费用:0.00

***Hand washing: cost per kg/item: 0.00, cost: 0.00.

和当我改变恒定5到双变量保持5中,(根据输入)打印

And when I change the constant 5 into a double variable holding 5, it prints (according to the input):

***手洗:每千克/项目费用:5.00,成本:20.00

***Hand washing: cost per kg/item: 5.00, cost: 20.00.

为什么会不断的5影响DTEMP的评价?我用gcc 4.6.2(MinGW的),并对其进行了测试也是在TCC。

Why would the constant 5 affect the evaluation of the dtemp? I'm using gcc 4.6.2 (MinGW) and tested it also in TCC.

推荐答案

我的编译器(GCC 4.4.3)警告信息说明这一点:

My compiler's (gcc 4.4.3) warning message explains this:

   format ‘%.2f’ expects type ‘double’, but argument 2 has type ‘int’

由于要在格式字符串传递不同类型的值大于指定( INT )(双击) ,该行为是不确定的,由于这种不匹配

Since you are passing a different type of value (int) than specified (double) in the format string, the behavior is undefined due to this mismatch

当你观察到的,一旦你适应这个是一致的,你得到你所期望的输出。即,

As you observed, once you adjust this to be consistent you get the output you expect. I.e.,

/* provide a double value */
printf("\n***Hand washing: cost per kg/item: %.2f, cost: %.2f.\n", 5.0, dtemp);

输出:

***Hand washing: cost per kg/item: 5.00, cost: 3.14.

/* specify an integer value in the format string */
printf("\n***Hand washing: cost per kg/item: %d, cost: %.2f.\n", 5, dtemp);

输出:

***Hand washing: cost per kg/item: 5, cost: 3.14.

总是一个好主意杀青编译器的警告级别,然后跟进所有的警告和对什么可以被忽略故意决定,哪些不能。

Always a good idea to crank up the warning levels on the compiler and then follow up on all warnings and make deliberate decisions about what can be ignored and what can't.

这篇关于互相影响的printf参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆