+1 vote
in Programming Languages by (66.2k points)

The following code does not return the correct result for division. The first printf() shows 6 whereas the second printf() shows 0.00 although I have used '%f' as format specifier. How to convert the type of n/2 so that it shows the correct result, 6.50.

#include <stdio.h>

int main() {

  int n = 13;              

  

  // Print variables

  printf("%d\n", n/2);

  printf("%.2f\n", n/2);

  return 0;

}

1 Answer

+3 votes
by (66.8k points)
selected by
 
Best answer

The output is correct. The C compiler will not convert the variable type just by specifying the format specifier. In this case, you need to manually convert by placing the type in parentheses () in front of the result.

In your example, you need to use (float)n/2 to get 6.50.

Here is the modified code:

#include <stdio.h>

int main() {

  int n = 13;              

  

  // Print variables

  printf("%d\n", n/2);

  printf("%.2f\n", (float)n/2);

  return 0;

}

Related questions

+1 vote
1 answer
+1 vote
1 answer
+2 votes
1 answer
+1 vote
1 answer

...