user9639282
user9639282

Reputation:

How to convert int to Double in C programming

int num1, num2;

double average;

average=(double)(num1+num2)/2;
printf("average: %d", average);

My test printf shows average as: 0

This is maybe too easy, but I can't see it. My inputs are both "int" and the average is "double" but somehow it is not calculating right ?

Upvotes: 0

Views: 42614

Answers (6)

Michael Talarczyk
Michael Talarczyk

Reputation: 1

If you want a floating point result, at least one of the operands must be a floating-point type

This is my solution:

average = (num1 + num2)/(double)2;

printf ("Value of 1/2 is: %.4f\n", (double)(1/2));
// Value of 1/2 is: 0.0000

printf ("Value of 1/2 is: %.4f\n", (1/(double)2));
// Value of 1/2 is: 0.5000

Upvotes: 0

John Bode
John Bode

Reputation: 123458

Integer division yields an integer result: 1/2 == 0, 5/3 == 1, etc. If you want a floating point result, at least one of the operands must be a floating-point type: 1/2.0f == 0.5f, 5/3.0 == 1.6667, etc.

So, you'll want to divide your sum by 2.0, not 2:

average = (num1 + num2)/2.0;

Secondly, you need to use the %f format specifier for floating-point output:

printf( "average: %f\n", average );

Upvotes: 2

Subhajit Mondal
Subhajit Mondal

Reputation: 31

You should use printf("average= %f",avearge); instead of using "%d" to print the average value.I think it will solve your issues...

Upvotes: 1

Achal
Achal

Reputation: 11921

No need to modify the statement average=(double)(num1+num2)/2; to get expected result inside printf use %f instead of %d

  • 1st (num1+num2) is performed, result of this is of integral type. lets say 15. Next when you do (double)15/2 result is of floating type which is 7.500000.
  • from previous step average = (double)7.500000 average holds 7.500000 but since you printed in %d you are getting 0 as its undefined behavior. instead use %f

Here is the working one

int main() {
        int num1 = 7, num2 = 8;
        double average;
        average = (double)(num1 + num2)/2;
        printf("average: %f\n", average);
        return 0;
} 

Upvotes: 4

dbush
dbush

Reputation: 223872

You're using the wrong format specifier to printf.

The %d format specifier expects an int argument, but you're passing a double. Using the wrong format specifier invokes undefined behavior.

To print a double, use %f.

printf("average: %f\n", average);

Upvotes: 6

abelenky
abelenky

Reputation: 64682

int num1, num2;
double average;
average=(num1+num2)/2.;            // Using a decimal point forces 2 to be a double.
printf("average: %f\n", average);  // Use the correct specifier for double: %f

Upvotes: 2

Related Questions