【问题标题】:How to round a number in C?如何在C中对数字进行四舍五入?
【发布时间】:2021-01-19 09:22:09
【问题描述】:

我尝试在 Stack Overflow 上搜索此问题,但找不到答案。

代码如下:

#include <stdio.h>

int main(void) {
 

double y;
printf("Enter a number: ");
scanf("%lf", &y);
printf("Your number when rounded is: %.2lf", y); 
//If user inputs 5.05286, how can i round off this number so as to get the output as 5.00
//I want the output to be rounded as well as to be 2 decimal places like 10.6789 becomes 11.00


return 0;
}

我要对一个数字进行四舍五入,比如数字是5.05286,应该四舍五入为5.00,如果是5.678901,则四舍五入为6.002小数位。数字5.678901 正在四舍五入为5.05,但它应该四舍五入为5。我知道我可以使用floor()ceil(),但我认为如果没有条件语句,我将无法完成答案,这不是我C 知识的范围。我也尝试使用round() 函数,但它根本不圆。

【问题讨论】:

  • floor(y*100+0.5)/100 怎么样,顺便说一句,5.05286 不是四舍五入到小数点后两位,只是5.05?仅将最后两位小数设为零并不是四舍五入到两位小数。您的描述适合 floor(y+0.5)。如果您意识到if x is over 0.5x + 0.5 &gt; 1 相同,则不需要条件。
  • 我也尝试使用 round() 函数,但它根本不舍入。 不知道你的意思 - 你只是使用类似 round(y); 的东西吗?那行不通,但y = round(y); 工作。
  • 您应该使用round 提供您的尝试。
  • “我也尝试使用 round() 函数,但它根本不舍入。” - 那你做错了什么

标签: c rounding


【解决方案1】:

您需要导入&lt;math.h&gt; 标头:

#include <math.h> //don't forget to import this !

double a;
a = round(5.05286); //will be rounded to 5.00

此函数对每种类型都有模拟定义,这意味着您可以传递以下类型,并且每种类型都会四舍五入到最接近的值:

double round(double a);
float roundf(float a);
long double roundl(long double a);

【讨论】:

    【解决方案2】:

    如果您不想使用任何额外的标题:

        float x = 5.65286;
        x = (int)(x+0.5);
        printf("%.2f",x);
    

    【讨论】:

    • 这对大数有明显的缺点,对负数效果不佳。
    猜你喜欢
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多