C++ 自己实现四舍五入函数

来源:互联网 发布:天府广场美食攻略 知乎 编辑:程序博客网 时间:2024/05/18 00:49

本文仅仅发布在CSDN我的博客:点击打开链接。

http://blog.csdn.net/pythontojava?viewmode=contents

转载请注明出处。

我用的IDE是VS2013.。代码在vc++6.0不能编译,要把int _tmain(int argc, _TCHAR* argv[]) 改成 int main() 。


1.float与double的四舍五入

#include<iostream>#include <math.h> using namespace std;float _45(float value, int n)//float类型的四舍五入函数 _45(float 值,第几位){float temp = value* pow(10, -n);//当n<0,程序表示精确到小数点后第|n|位temp = floor(temp + 0.5);//当n=0,表示四舍五入只保留数的整数部分return (temp * pow(10, n));}double _45(double value, int n)// double类型的四舍五入函数,_45(float 值,第几位){double temp = value* pow(10, -n);//当n<0,程序表示精确到小数点后第|n|位temp = floor(temp + 0.5);//当n=0,表示四舍五入只保留数的整数部分return (temp * pow(10, n));}int _tmain(int argc, _TCHAR* argv[]){float a = 158.55;float b = 111.44;cout <<a<<"->"<<_45(a,-1)<<endl;//小数点后一位cout << b<< "->" << _45(b,-1);cout << endl;system("pause");return 0;}

==========分割线==========

用函数模板实现

#include "stdafx.h"#include<iostream>#include <math.h> using namespace std;template<typename T>T  _45(T x, int n){T temp = x * pow(10, -n);temp = floor(temp + 0.5);return (temp * pow(10, n));}int _tmain(int argc, _TCHAR* argv[]){float a = 158.55;double b = 211.13;cout <<_45<float>(a,-1)<<endl;cout << _45(b, -1) << endl;system("pause");return 0;}

0 0
原创粉丝点击