来源
本文给出使用标准库函数round()的方案
在math.h中提供了能直接进行四舍五入的函数。
直接使用round()不能达到题目的效果,因为round函数仅使用小数点后一位进行判定,若小数点后一位大于等于5则进位且返回X.0,不能满足保留两位小数。
所以想要使用round函数进行四舍五入,我们需要经过一些简单的处理:
①对数字放大,将想要保留的小数部分移到整数部分
②使用round函数进行四舍五入
③将数字缩小,得到理想的结果
具体代码实现如下:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <math.h>
int main() {
double num = 0; // 要四舍五入的数字
scanf("%lf", &num);
int decimal_places = 2; // 保留2位小数
double factor = pow(10, decimal_places);//这段代码的意思是10的decimal_placesdecimal_places(2)次方。
double scaled = num * factor; // 如3.14159 * 100 = 314.159,这里即是移位操作。
scaled = round(scaled);//四舍五入,314.0
double result = scaled / factor;//除100,变回3.140
printf("%.2f", result);//输出3.14
}
如有疏漏欢迎在评论区指出