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);
float a_4decimal = round(a * pow(10, 4)) * pow(10, -4);
float a_5decimal = round(a * pow(10, 5)) * pow(10, -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
- 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
|