简体   繁体   中英

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

In the second case you are correctly passing in int and since you are assigning the result to money :

money=money+money*0.4

it will truncate the double value. 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:

warning: format '%d' expects argument of type 'int', but argument 2 has type '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:

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.

Check the multiplication in line 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成为该值的错误格式说明符。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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