在c ++中截断十进制值 [英] Truncate a decimal value in c++

查看:109
本文介绍了在c ++中截断十进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将值为0.6000002的c ++ float变量截断为值0.6000并将其存回变量中的最简单的方法是什么?

What's the easiest way to truncate a c++ float variable that has a value of 0.6000002 to a value of 0.6000 and store it back in the variable?

提前感谢!

推荐答案

首先,重要的是要知道浮点数是近似的。请参阅@Greg Hewgill提供的链接,了解为什么这个问题不能完全解决。

First it is important to know that floating point numbers are approximated. See the link provided by @Greg Hewgill to understand why this problem is not fully solvable.

但这里有一些解决方案,可能会满足你的需要:

But here are a couple of solutions to the problem that will probably meet your need:

方法但效率较​​低:

char sz[64];
double lf = 0.600000002;
sprintf(sz, "%.4lf\n", lf); //sz contains 0.6000

double lf2 = atof(sz);

//lf == 0.600000002;
//lf2 == 0.6000

printf("%.4lf", lf2); //print 0.6000

更高效的方法,但可能不太精确:

The more efficient way, but probably less precise:

double lf = 0.600000002;
int iSigned = lf > 0? 1: -1;
unsigned int uiTemp = (lf*pow(10, 4)) * iSigned; //Note I'm using unsigned int so that I can increase the precision of the truncate
lf = (((double)uiTemp)/pow(10,4) * iSigned);

这篇关于在c ++中截断十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆