在实现数据四舍五入时,可以选择取到最末一位有效数字的后一位(记为last_num),并比较last_num与“5”的大小,再进行相应的操作以实现四舍五入的功能。
(PS:文章作者所用编译器为Visual Studio 2019)
一.取指定位上数字
通过不断对原数字进行“10”的模除,逐渐接近目标位数,然后再用除法,得到目标位上的数字。
例1::取十进制正整数test_num的百位上数字
①方法1:直接取数
int test_num = 54863;
int temp = test_num;
while (temp / 1000 != 0)
{
temp = temp % 10;
}
//while循环结束后,temp的值为test_num的百位、十位和个位值,即863
temp = temp / 100;
//此时temp的值为test_num的十位上的数字,即8
②方法2:从前取数(先取到548)
int test_num = 54863;
int temp = test_num / 100;
while (temp / 10 != 0)
{
temp = temp % 10;
}
//while循环结束后,temp的值为temp初始值的个位值,即test_num的百位上的数字8
③方法3:从后取数(先取到863)
int test_num = 54863;
int temp = (test_num % 1000) / 100;
//此时temp的值为test_num的百位上的数字8
例2:取十进制正小数test_num的小数点后3位上数字
double test_num = 36.1543895;
long int temp = test_num*1000;
while (temp / 10 != 0)
{
temp = temp % 10;
}
//while循环结束后,temp的值为temp初始值的个位上数字,即test_num的小数点后3位上的数字4
二.四舍五入的实现
以test_num四舍五入取小数点后5位为例:
double test_num = 156.3415384;
long int temp;
double result_num;
int last_num = 8; //已取到小数点后6位上的数字
if (last_num >= 5)
{
temp = (long int)(test_num * 100000 + 1);
result_num = (double)temp / 100000;
}
printf("%.5lf", result_num);
上面的做法是将test_num小数点后5位之后的所有数字全部丢弃。
然而在实现具体功能的时候,不一定非要这样做,如果要实现的功能只是把四舍五入后的数字打印出来,那么代码可以是这样:
double test_num = 156.3415384;
printf("%.5lf", test_num);