C++浮点数转换为定点数

  笔者最近在编程的时候,要控制浮点数的精度进行计算和对比,在网上经过一系列查找后终于

在Csdn上面找到了相关的内容,虽然控制浮点数的精度后没有性能上的提升,笔者知道了如何修改

和控制浮点数的精度了,总的来说,每天要进步一点点。

代码如下:

 1 #include "cuda_runtime.h"
 2 #include "device_launch_parameters.h"
 3 
 4 #include <stdio.h>
 5 
 6 #include <iomanip>
 7 #include <sstream>
 8 #include <iostream>
 9 #include <cmath>
10 
11 // 功能:四舍五入(double),支持正负数
12 // dSrc : 待四舍五入之数
13 // iBit : 保留的小数位数。 0 - 不保留小数、1 - 保留一位小数
14 // 返回值:返回计算结果
15 // 
16 double Round(_In_ double dSrc, _In_ int iBit)
17 {
18     double retVal = 0.0;
19     int  intTmp = 0;
20 
21 
22     // 若保留小数位数不正确
23     if (0 > iBit )
24     {
25         return 0;
26     }
27 
28         //  若 为负数
29         if (0 > dSrc)
30         {
31             // 首先转为正数
32             dSrc *= -1;
33 
34             intTmp = (int)((dSrc + 0.5 / pow(10.0, iBit)) * pow(10.0, iBit));
35             retVal = (double)intTmp / pow(10.0, iBit);
36 
37             // 再转为 负数
38             retVal *= -1;
39         }
40 
41             // 若为非负数
42         else
43         {
44             intTmp = (int)((dSrc + 0.5 / pow(10.0, iBit)) * pow(10.0, iBit));
45             retVal = (double)intTmp / pow(10.0, iBit);
46         }
47 
48     // 返回计算结果
49     return retVal;
50 }
51 
52 
53 template<typename T>
54 T Round(T dSrc, int iBit) {
55     //若保留小数位数小于0,则返回0
56     if (0 > iBit) {
57         return 0;
58     }
59     ////////////////////////////////////
60     T retVal = 0.0f;
61     int tmp = 0;
62 
63     //1.若小于0
64     if (0 > dSrc) {
65         //转为非负
66         dSrc *= -1;
67         tmp= (int)((dSrc + 0.5 / pow(10.0, iBit)) * pow(10.0, iBit));
68         retVal = ((T)tmp)/ pow(10.0, iBit);
69 
70         //还原
71         dSrc *= -1;
72     }
73     else//2.若大于>0
74     {
75         tmp = (int)((dSrc + 0.5 / pow(10.0, iBit)) * pow(10.0, iBit));
76         retVal = ((T)tmp) / pow(10.0, iBit);
77     }
78     return retVal;
79 }
80 
81 int main(void) {
82     double pi = 3.1415926;
83     double temp = 0;
84     float test= 35.569999999;
85     temp=Round<float>(pi, 2);
86     //std::cout << temp << std::endl;
87     //printf("tmp=%f\n", temp);
88 
89     return 0;
90 }
precision

猜你喜欢

转载自www.cnblogs.com/xuelanga000/p/12407121.html