-1

我尝试在 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()and ceil(),但我认为如果没有条件语句,我将无法完成答案,这不是我的C知识范围。我也尝试使用该round()功能,但它根本不圆。

4

3 回答 3

4

您需要导入<math.h>标头:

#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);
于 2021-01-19T09:28:13.173 回答
0

如果您不想使用任何附加标头:

    float x = 5.65286;
    x = (int)(x+0.5);
    printf("%.2f",x);
于 2021-01-19T09:43:26.273 回答
-1

我在堆栈溢出中找到了这个片段并且它有效

(int)(num < 0 ? (num - 0.5) : (num + 0.5))

如何将浮点数舍入到C中最接近的整数?

 #include <stdio.h>
    #include <math.h> 
    int main(void) {
     
    
    double y;
    printf("Enter a number: ");
    scanf("%lf", &y);
    y=(int)(y < 0 ? (y - 0.5) : (y + 0.5));
    printf("Your number when rounded is: %.2lf", y); 
    
    
    
    return 0;
    }
于 2021-01-19T09:45:00.273 回答