Output of code in C. Programming in C. Please help.?

Home » Programming & Design » Output of code in C. Programming in C. Please help.?
Programming & Design No Comments

What is the output of the following if a=3, b=8, c=7?
d = 5 * (a + b) / (a + c);
printf("Result is %.1f", d);

I got Result is 5. It is wrong.

Other answer:

Kanaynay:
The problem is caused by using 5 rather than 5.0.

If the values on the right of the expression are all defined or entered as integers, then it will compute an integer value. This integer value will be converted to a float after it is calculated. By using 5.0. you force the right side to be calculated as floats and the integer values for a, b and c will be converted to floats before they are used.

I hope this explains it.

Khairul:
If the values on the right of the expression are all defined or entered as integers, then it will compute an integer value. This integer value will be converted to a float after it is calculated. By using 5.0. you force the right side to be calculated as floats and the integer values for a, b and c will be converted to floats before they are used.

I hope this explains it.

Andi:
Seems to give 5.5 when I run it….

https://ideone.com/dmcB2U

#include <stdio.h>

float a=3, b=8, c=7 ;
float d;

void main()
{

d = 5 * (a + b) / (a + c);

printf("Result is %.1f\n", d);
printf("Result is %.1f\n", &d);
}

That said… if I declare

int a=3, b=8, c=7 ;
float d;

https://ideone.com/48orqp
I do and will get 5.0
because the whole calculation is done as INT (5 is int, 5.0 is float)
d = 5 * (a + b) / (a + c);

—-
now use 5.0 (a float !) to multiply, and it will cast the result as float
d = 5.0 * (a + b) / (a + c);

https://ideone.com/qAFW81

and it goes back to 5.5 again

John:
Compile it and run it.

I got 5.5 But which data types did you assign to ABCD?

My guess ABC int and D Double(or its less precise cousin Float)

Shirley:
The correct answer is 5.5, The data type used to declare may be different.
Andy T:
The issue is data type, those as int or float?
Hristo:
You need to talk with Programist for this.

LEAVE A COMMENT