当前位置: 代码迷 >> 综合 >> C++实现四舍五入
  详细解决方案

C++实现四舍五入

热度:94   发布时间:2023-10-23 04:10:15.0

一、round()函数介绍

1.头文件#include<math.h>

2.功能只能四舍五入保留至整数

二、四舍五入,保留至整数

#include<iostream>
#include<math.h>
using namespace std;
int main()
{float a = 1.0/3;float b = 2.0/3;float c = -1.0/3;float d = -2.0/3;cout<<a<<"四舍五入(保留至整数):"<<round(a)<<endl; // 0cout<<b<<"四舍五入(保留至整数):"<<round(b)<<endl; // 1cout<<c<<"四舍五入(保留至整数):"<<round(c)<<endl; // -0cout<<d<<"四舍五入(保留至整数):"<<round(d)<<endl; // -1return 0; } 

三、四舍五入,保留n位小数

1.实现方法:round(float_value * pow(10, n)) * pow(10, -n)

先将待处理数据乘以10^n,然后使用round函数四舍五入,最后乘以10^(-n)。

#include<iostream>
#include<math.h>
using namespace std;
int main()
{int n;float a = 1.0/3;float b = 2.0/3;float c = -1.0/3;float d = -2.0/3;cin>>n;cout<<a<<"四舍五入(保留至"<<n<<"位小数):"<<round(a * pow(10, n)) * pow(10, -n)<<endl;cout<<b<<"四舍五入(保留至"<<n<<"位小数):"<<round(b * pow(10, n)) * pow(10, -n)<<endl;cout<<c<<"四舍五入(保留至"<<n<<"位小数):"<<round(c * pow(10, n)) * pow(10, -n)<<endl;cout<<d<<"四舍五入(保留至"<<n<<"位小数):"<<round(d * pow(10, n)) * pow(10, -n)<<endl;return 0; /*  运行结果 40.333333四舍五入(保留至4位小数):0.33330.666667四舍五入(保留至4位小数):0.6667-0.333333四舍五入(保留至4位小数):-0.3333-0.666667四舍五入(保留至4位小数):-0.6667*/}