简体   繁体   English

使用 printf() 到 output 正确的小数位数?

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

When I enter 2 , I wish to get this output:当我输入2时,我希望得到这个 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.您可以使用%.Nf指定要在小数点后打印的位数,其中N是小数点后的位数。 In your use case, %.1f : printf("Result: %.1f", result) .在您的用例中, %.1fprintf("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.您正在使用scanf() ,但您没有检查它的返回值。 This may cause your code to break.这可能会导致您的代码中断。

scanf() returns the number of arguments it successfully parsed . scanf()返回它成功解析的 arguments 的数量。 If, for any reason, it fails, it doesn't alter the arguments you gave it, and it leaves the input buffer intact .如果出于任何原因它失败了,它不会改变你给它的 arguments,它会保持输入缓冲区完好无损 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.要解决此问题,您需要清除输入缓冲区以防scanf()失败。 By clearing the buffer, I mean read and discard everything up until a newline (when you previously pressed Enter ) is encountered.通过清除缓冲区,我的意思是读取并丢弃所有内容,直到遇到换行符(当您之前按下Enter时)。

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:你可以像这样在你的 main 中使用它:

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:样本 output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM