简体   繁体   中英

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:

#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?

You can specify how many digits you want to print after the decimal point by using %.Nf where N is the number of digits after the decimal point. In your use case, %.1f : printf("Result: %.1f", result) .


There are some other issues in your code. You are making use of scanf() , but you are not checking its return value. This may cause your code to break.

scanf() returns the number of arguments it successfully parsed . If, for any reason, it fails, it doesn't alter the arguments you gave it, and it leaves the input buffer intact . This means whenever you try again and read from the input buffer, it will automatically fail since

  • it previously failed to parse it, and
  • it didn't clear it, so it's always there.

This will result in an infinite loop.

To solve the issue, you need to clear the input buffer in case scanf() fails. By clearing the buffer, I mean read and discard everything up until a newline (when you previously pressed Enter ) is encountered.

void getfloat(const char *message, float *f)
{
    while (true) {
        printf("%s: ", message);
        int rc = scanf("%f", f);
        if (rc == 1 || rc == EOF) break; // Break if the user entered a "valid" float number, or EOF is encountered.
        scanf("%*[^\n]"); // Read an discard everything up until a newline is found.
    }
}

You can use it in your main like that:

int main(void) // Note the void here when a function doesn't take any arguments
{
    float num;
    float result;
    
    getfloat("Number", &num);
    
    result = num * 1.2;
    printf("Result: %.1f", result); // Print only one digit after the decimal point.
}

Sample output:

Number: x
Number: x12.45
Number: 12.75
Result: 15.3

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