如何在C中舍入一个数字?

How to round a number in C?

我尝试在 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.00,小数位 2。数字 5.678901 正在四舍五入为 5.05,但它应该四舍五入为 5。我知道我可以使用 floor()ceil(),但我认为如果没有条件语句我将无法完成答案,这不是我的 C 的范围知识。我也尝试使用 round() 函数,但它根本不四舍五入。

您需要导入 <math.h> header :

#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);

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

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