【C】如何取到数字的指定位上数字并实现数字的四舍五入

在实现数据四舍五入时,可以选择取到最末一位有效数字的后一位(记为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);

本文完。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值