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

本文仅仅发布在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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值