筆者最近在編程的時候,要控制浮點數的精度進行計算和對比,在網上經過一系列查找后終於
在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 }