C++ 四舍五入以及保留几位有效数字

Problem

计算过程中发现,如果不控制保留的小数有效数字,会出现求出nan的情况,因此,需要限制保留的小数位数

Solution

#include<iostream>
#include<math.h>
using namespace std;

int main()
{
	float a = 1.0/3;
	float a_3decimal = round(a * pow(10, 3)) * pow(10, -3)//3位小数
	float a_4decimal = round(a * pow(10, 4)) * pow(10, -4)//4位小数
	float a_5decimal = round(a * pow(10, 5)) * pow(10, -5)//5位小数

	printf("a_3decimal=%lf\n",a_3decimal);
	printf("a_4decimal=%lf\n",a_4decimal);
	printf("a_5decimal=%lf\n",a_5decimal);
	
	return 0; 
 } 

Output:

a_3decimal=0.333000
a_4decimal=0.333300
a_5decimal=0.333330

Reference

  1. C++的四舍五入函数:https://blog.csdn.net/qq_34950042/article/details/104365637?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-3.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-3.no_search_link
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值