2014-09-28 51 views
1

我編碼類的簡單程序。我已經完成了,不用擔心,我不會要求任何人做我的功課。讓我用一個例子來解釋我想要的。表現出一定的小數位ç

我的程序要求的比特量,並將其轉換到MB,kb和字節。因此,如果輸出I輸入1位是:

1 in megabytes is: 0.000000119209290 
1 in kilobytes is: 0.000122070312500 
1 in bytes is: 0.125000000000000 
1 in bits is: 1 

所以,我的問題是,只是一個審美的一個:我怎麼能不顯示小數位是不必要的?例如,在字節,我想只有打印0.125,而不是15位小數,這是不是漂亮的。

的源代碼是:

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

int main(void) 
{ 

     unsigned long long int bits; 

     printf("Input a quantity of bits: \n"); 
     scanf("%lld", &bits); 

    /* 
    * 1 byte = 8 bits. 
    * 1 kilobyte = 1024 bytes. 
    * 1 megabyte = 1024 kilobytes. 
    */ 
     long double by = ((double) bits)/((double) 8); 
     long double kb = ((double) by)/((double) 1024); 
     long double mb = ((double) kb)/((double) 1024); 

     printf("%lld in megabytes is: %.15Lf\n", bits, mb); 
     printf("%lld in kilobytes is: %.15Lf\n", bits, kb); 
     printf("%lld in bytes is: %.15Lf\n", bits, by); 
     printf("%lld in bits is: %lld\n", bits, bits); 

    return(0); 
} 

PS:我知道我指定的15位小數在printf,我赤身只是想這是最好的辦法,我輸出的值。

預先感謝您!

+0

http://stackoverflow.com/questions/277772/avoid-trailing-zeroes-in-printf 這可能會幫助你。 – venki421 2014-09-28 13:53:13

+0

thig是使用%g我得到兆字節作爲指數,我想要一個小數。 – 2014-09-28 13:55:58

+0

您是否閱讀過[printf(3)](http://man7.org/linux/man-pages/man3/printf.3.html) – 2014-09-28 13:56:14

回答

1

你可以做一個函數來計算所需的小數位數。要做到這一點,取小數部分,並乘以10,直到它變成一個整數。

int required_decimal_places(double x) 
{ 
    int counter = 0; 

    x -= floor(x); 
    while (x != floor(x)) 
    { 
     x *= 10; 
     ++counter; 
    } 

    return counter; 
} 

然後,輸出的與所需數量的小數點後的位數:

printf("%lld in megabytes is: %.*f\n", bits, required_decimal_places(mb), mb); 

在格式字符串中的星號(*)告訴輸出的長度被指定爲一個參數的系統。

注意:我在您的代碼中將long double替換爲double,因爲我不確定在上調用庫函數floor是否正確。我也在格式化字符串中將Lf更改爲f。在這裏進行的計算中不需要額外的精度long double(如果有的話)。

+0

這是一個非常genious,這是我最終使用的。非常感謝你! – 2014-09-28 17:17:51

4

使用g符,就像這樣:

printf("%lld in megabytes is: %.15Lg\n", bits, mb); 
printf("%lld in kilobytes is: %.15Lg\n", bits, kb); 
printf("%lld in bytes is: %.15Lg\n", bits, by); 
printf("%lld in bits is: %lld\n", bits, bits); 

然而,如果需要的話,這將使用科學記數法。您可以添加一條if語句,如下所示:

if(fmod(mb, 10) == mb // last digit is not zero 
    && mb < 0.000001) // if mb is a small number (the left value may need tuning) 
    printf("%lld in megabytes is: %.15Lf\n", bits, mb); 
else 
    printf("%lld in megabytes is: %.15Lg\n", bits, mb); 

相關答案是this。另請注意,我不得不使用FMOD()(下math.h中),因爲mb整數。

+0

謝謝!這很好地解決了它! – 2014-09-28 16:49:57

+0

歡迎您@IgnasiSánchez。你也提出了一個很好的問題,因此我的+1。 :) – gsamaras 2014-09-28 18:24:26

0

的可能方式可能是打印成一個字符串,然後檢查字符串是不夠準確:

double x= some_number(); 
char buf[48]; 
snprintf (buf, sizeof(buf), "%.3f", x); 
if (atof(buf) == x) puts(buf); 
else { 
    snprintf (buf, sizeof(buf), "%.6f", x); 
    if (atof(buf) == x) puts(buf); 
    else printf("%.15g", x); 
} 

floating point guide;考慮與某些epsilon進行比較,例如if (abs(x-atof(buf)) < 1.0e-5*abs(x))

順便說一句,請注意bignum -s,如果需要很多(超過8個)小數,請考慮GMPlib