简体   繁体   English

使用printf时出现意外结果

[英]Unexpected results when using printf

I am seeing different results for two program that I expect to produce the same output, the first case: 我看到两个程序的不同结果,我期望产生相同的输出,第一种情况:

int money;

printf("Enter the price of the car: ");
scanf("%d", &money);

printf("\nResult: %d .\n", money+money*0.4);

the second case: 第二种情况:

int money;

printf("Enter the price of the car: ");
scanf("%d", &money);

money=money+money*0.4;

printf("\nResult: %d .\n", money );
return 0;

In the first case the result of the printf is 0 but not in the second case. 在第一种情况下, printf的结果为0但在第二种情况下不是。 Why am I seeing these different results? 为什么我看到这些不同的结果?

the %d format specifier tells printf that you are passing in an int but in the first case you are passing in a double which is also undefined behavior and so the results are not reliable. %d格式说明符告诉printf您正在传入一个int,但在第一种情况下,您传入的是double ,这也是未定义的行为 ,因此结果不可靠。 The result of: 的结果:

money+money*0.4

is double since a floating constant is double unless it has a suffix such as f and the results of the multiplication and addition are double as well due to the usual arithmetic conversions which both operations are subject to and which will cause the value of money to be converted to double for the operation. 因为浮动常数除非它有一个后缀如f乘法加法的结果是以及由于通常算术转换这两种操作都受到和这将导致的值money是为操作转换为double

In the second case you are correctly passing in int and since you are assigning the result to money : 在第二种情况下,您正确地传入int ,因为您要将结果分配给money

money=money+money*0.4

it will truncate the double value. 它将截断double值。 I am not sure what compiler you are using but both clang and gcc without any warning flags both warn about the incorrect format specifier, gcc for example says: 我不确定你使用的是什么编译器但是没有任何警告标志的clanggcc都警告不正确的格式说明符,例如gcc说:

warning: format '%d' expects argument of type 'int', but argument 2 has type 'double' [-Wformat] 警告:格式'%d'需要类型为'int'的参数,但参数2的类型为'double'[-Wformat]

So if you are not seeing any warning for that line you should look into setting your warning levels higher. 因此,如果您没有看到该线路的任何警告,您应该考虑设置更高的警告级别。

For completeness sake the draft C99 standard section 7.19.6.1 The fprintf function , which also covers printf with respect to the format specifiers, In paragraph 9 says: 为了完整起见, 草案C99标准7.19.6.1fprintf函数 ,其中也包括关于格式说明符的printf ,在第9段中说:

If a conversion specification is invalid, the behavior is undefined. 如果转换规范无效,则行为未定义。 248) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined. 248)如果任何参数不是相应转换规范的正确类型,则行为未定义。

Check the multiplication in line 7. 检查第7行的乘法。

You could change the last lines to: 您可以将最后一行更改为:

float price = money * 1.4;
printf( "\nResult %f.\n", price);

money+money*0.4将隐含地将money转为double,从而使%d成为该值的错误格式说明符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM