2

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?

1
  • 1
    You should enable warning to understand. In first case it is format ‘%d’ expects type ‘int’, but argument 2 has type ‘double’ In second case conversion to ‘int’ from ‘double’ may alter its value. And i guess warning explains itself very well. Commented Oct 28, 2013 at 11:56

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Check the multiplication in line 7.

You could change the last lines to:

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

Comments

1

money+money*0.4 will implicitly cast money to double and thus make the %d a wrong format specifier for that value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.