【问题标题】:How to only display decimal points to 2 decimal places only when there aren't trailing zeroes [duplicate]仅当没有尾随零时,如何仅将小数点显示为 2 位小数[重复]
【发布时间】:2015-02-27 12:20:54
【问题描述】:

我一直在尝试将小数点显示到小数点后 2 位以进行乘法运算:

if (operation == multiplication)
    {
        printf("\n\n            You have chosen to perform a multiplication operation\n\n");
        printf("Please enter two numbers seperated by a space (num1 * num2): ");
        scanf("%f %f", &number1, &number2);

        total = number1 * number2;

        printf("\n%f times %f is equal to: %f", number1, number2, total);
    }

所以如果我输入 0.5 & 30 我会得到 15 而不是 15.000000 如果我输入 0.5 & 15 我会得到 7.50 而不是 7.5000000。

我对 C 和一般情况下的编程还是很陌生,所以详细的解释真的很棒。 谢谢。

【问题讨论】:

    标签: c


    【解决方案1】:

    printf 与精度说明符一起使用:

    #include <stdio.h>
    #include <math.h>
    
    int main(void)
    {
        double x = 10.0, y = 10.5, dummy;
    
        printf("%.*f\n", (modf(x, &dummy) == 0) ? 0 : 2, x);
        printf("%.*f\n", (modf(y, &dummy) == 0) ? 0 : 2, y);
        return 0;
    }
    

    输出:

    10
    10.50
    

    【讨论】:

    • 有没有办法让它从用户那里获取 x 和 y 的值?
    • 你已经在你的代码 sn-p 中使用了这个函数 (scanf),你为什么要问这个?
    【解决方案2】:

    只需像这样指定小数位:

    printf("\n%.2f times %.2f is equal to: %.2f", number1, number2, total); 
             //^^See here ^^                ^^
    

    有关printf() 的更多信息,请参见此处:http://www.cplusplus.com/reference/cstdio/printf/

    【讨论】:

      猜你喜欢
      • 2019-11-26
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多