Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using printf() to output the correct number of decimal places?

When I enter 2, I wish to get this output:

value: 2.4

But when I do the multiplication, I am getting this:

value: 2.400000

This is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <stdio.h>

int main()
{
  float num;
  float result;
  
  printf("Number: ");
  scanf("%f", &num);
  
  result = num * 1.2;
  printf("Result: %f", result);
}

What can I do?

>Solution :

You need to change your printf() to this:

printf("Result: %.1f", result);

The number after the . and before the f is the precision that specifies the number of digits after the decimal point of a floating-point value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading