printf parameters affecting each other

假如想象 提交于 2020-01-04 06:51:09

问题


I have the following code:

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

It prints out:

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

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

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

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.


回答1:


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

   format ‘%.2f’ expects type ‘double’, but argument 2 has type ‘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);

output:

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

or

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

output:

***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.




回答2:


f conversion specifier requires a double when used with printf functions and your are passing an int. Passing an int is undefined behavior which means anything can happen.




回答3:


e the printf function first parameter is string, it check every %d,then move the point,for example: %d,move 4 len; %lld move 8. int64_t a = 1;int b = 2; printf("%d, %d\n", a, b); the answer is 1,0. because the two %d just get the a lower 4 byte and hight 4 byte.

printf("\n***Hand washing: cost per kg/item: %.2f, cost: %.2f.\n", 5, dtemp); sizeof(doubel) = 8 ,so the printf function just get 0x0000000000000005.

I hope it would help you.



来源:https://stackoverflow.com/questions/11382694/printf-parameters-affecting-each-other

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!