简体   繁体   中英

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?

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);

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;
} 
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

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

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 );

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

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