2013-06-04 26 views
-3

我對此問題感興趣。
我得到了一些變量,如下所示的雙精度值:在c編程中舍入長整數十進制值

a = 0.76271469999999997000 
b = 0.66698279999999999000 
c = 0.34262199999999998000 

我需要這些輪對

rounded_a = 0.762714700000000 
rounded_b = 0.666982800000000 
rounded_c = 0.342622000000000 

我應該如何去這樣做呢?

+2

你可以在這裏找到你的答案... [鏈接](http://stackoverflow.com/questions/497018/is-there-a - 功能對一個浮動在C或做,我需要寫我自己的) – Paritosh

+1

請注意,該鏈接,和其他相關的答案,可以在側邊欄中找到對。 –

+0

非常強烈的認可上面的鏈接! – xaxxon

回答

-1

這裏是我使用的代碼:

int64_t __pow10_arr[18] = { 1l, 10l, 100l, 1000l, 10000l, 100000l, 
          1000000l, 10000000, 100000000l, 1000000000l, 10000000000l, 100000000000l, 
          1000000000000l, 10000000000000l, 100000000000000l, 1000000000000000l, 10000000000000000l, 100000000000000000l }; 

double roundToNfractions (double val, int n) 
{ 
    if (n<0 || n >= (sizeof (__pow10_arr)/ sizeof (int64_t))) { 
    // log error however you wish to 
    return val; 
    } 
    val *= __pow10_arr[n]; 
    val += 0.5; 
    val = (uint64_t) val; 
    val /= __pow10_arr[n]; 
    return val; 
} 
+1

你能保證他想要的值甚至可以直接用二進制浮點表示嗎?我建議他試着更好地理解浮點數,以便意識到他需要使用別的東西或調整他的方法。 – xaxxon

+0

以及爲什麼你會乘以10?你很可能失去精確度。 – xaxxon

+0

我能想到的唯一合理方法是打印出該值並將其作爲文本處理問題處理。但是如果你試圖把它放回到一個字符串的double中,你仍然可能會遇到問題。 – xaxxon

0
#include <stdio.h> 
#include <math.h> 

double round_n(double x, int n){ 
    double wk; 
    wk = pow(10.0, (double)n); 
    return round(x * wk)/wk;//c99 function 
} 

int main(void){ 
    double a, b, c; 
    a = 0.76271469999999997000; 
    b = 0.66698279999999999000; 
    c = 0.34262199999999998000; 
    a = round_n(a, 7); 
    b = round_n(b, 7); 
    c = round_n(c, 7); 
    printf("a=%.8lf\nb=%.8lf\nc=%.8lf", a, b, c); 
    return 0; 
}