Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why result of (double + int) is 0 (C language)

Tags:

c

int

double

result of

printf("%d\n", 5.0 + 2);

is 0

but

int num = 5.0 + 2;
printf("%d\n", num);

is 7

What's the difference between the two?

like image 742
PWS Avatar asked Jan 31 '19 12:01

PWS


People also ask

Is double %D in C?

%d stands for decimal and it expects an argument of type int (or some smaller signed integer type that then gets promoted). Floating-point types float and double both get passed the same way (promoted to double ) and both of them use %f .

How is double declared in C?

We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.

What is a double * in C?

Updated on April 27, 2019. The double is a fundamental data type built into the compiler and used to define numeric variables holding numbers with decimal points. C, C++, C# and many other programming languages recognize the double as a type. A double type can represent fractional as well as whole values.

What is the result of 1/2 in Java?

When you do 1/2 that is integer division because two operands are integers, hence it resolves to zero (0.5 rounded down to zero). If you convert any one of them to double, you'll get a double result. Show activity on this post. 1 and 2 are both integers, so 1 / 2 == 0 .


2 Answers

The result of 5.0 + 2 is 7.0 and is of type double.

The "%d" format is to print int.

Mismatching format specification and argument type leads to undefined behavior.

To print a float or double value with printf you should use the format "%f".


With

int num = 5.0 + 2;

you convert the result of 5.0 + 2 into the int value 7. Then you print the int value using the correct format specifier.

like image 79
Some programmer dude Avatar answered Oct 03 '22 04:10

Some programmer dude


In all expressions, every operand has a type. 5.0 has type double. 2 has type int.

Whenever a double and an integer are used as operands of the same operator, the integer is silently converted to a double before calculation. The result is of type double.

And so you pass double to printf, but you have told it to expect an int, since you used %d. The result is a bug, the outcome is not defined.

But in case of int num = 5.0 + 2;, you first get a result as double, 7.0. Then force a conversion back to int. That code is equivalent to:

int num = (int)((double)5.0 + (double)2);

More details here: Implicit type promotion rules

like image 37
Lundin Avatar answered Oct 03 '22 02:10

Lundin