C语言中,可以使用以下方法实现四舍五入:
double round(double x);
例如:
double num = 6.8;
double rounded_num = round(num);
printf("%f\n", rounded_num); // 输出 7.0
例如:
double num = 6.8;
double rounded_num = floor(num + 0.5);
printf("%f\n", rounded_num); // 输出 7.0
例如:
double num = 6.8;
int int_num = (int)num;
double diff = num - int_num;
double rounded_num;
if (diff >= 0.5) {
rounded_num = int_num + 1;
} else {
rounded_num = int_num;
}
printf("%f\n", rounded_num); // 输出 7.0