2016-06-10 40 views
0

我需要關於如何格式化C++中的輸出以顯示小數位(如果有)的幫助,或者在沒有小數點時顯示整數顯示。當C++中有小數值時,爲浮點值格式化輸出

it should show 95.7 // When there is decimal 
it should show 90 // When there is no decimal 

我寫道:

cout << setprecision(1) << fixed; 

它不給我預期的輸出。而不是打印90,它打印90.0

+0

那麼你的問題是什麼?你面臨什麼錯誤? –

+0

只需'std :: cout << 95.7 <<''<< 90.0 <<'\ n';'默認顯示您請求的值。你真的沒有寫一些代碼,看看?如果你的代碼不起作用,請發佈它並向我們顯示你實際獲得的輸出。 –

+0

當我寫:cout << setprecition(1)<< fixed。它沒有給我預期的產出。它不是打印90,而是打印90.0 – Allen

回答

1

假設你正在執行部門。

  1. 使用cout
    我)如果小數部分變成是.000000,然後用cout將只打印整數(整個數字)的一部分。
    ii)如果小數部分結果不是.000000,那麼cout也會打印小數部分。

    因此,在這兩種情況下,cout都會導致您需要的行爲。

  2. 使用printf()
    ⅰ)如果小數部分原來是.000000,然後使用printf()將打印整數,隨後的小數部分,例如,3.000000。在這種情況下,您將手動處理它,以便只輸出3。您可以使用不同的方法,如轉換爲字符串,使用內置函數等。
    ii)如果小數部分不是.000000,那麼printf()將打印輸出,如3.123456

請參閱下面的代碼。我使用的事實是,如果餘數爲0,則表示小數部分爲.000000,並在打印數字之前將數字類型轉換爲int。您可能必須使用上面指出的不同方法。

#include <iostream> 
#include <cstdio> 
using namespace std; 

int main() { 
    double num1=270.0, num2=90.0; 
    cout<<num1/num2<<"\n";      //prints just 3 
    printf("%f\n", num1/num2);     //prints 3.000000 
    if((int)num1%(int)num2==0)     //means num1 is a multiple of num2. So decimal is .000000 
     printf("%d\n", (int)num1/(int)num2);  

    num2=91.0; 
    cout<<num1/num2<<"\n";      //prints 2.96703 
    printf("%f\n", num1/num2);     //prints 2.967033 
    if((int)num1%(int)num2!=0)     
     printf("%f\n", num1/num2); 
    return 0; 
} 

現場演示here

1

您可以創建一個函數,將float轉換爲只有一個小數位。然後測試浮子是否等於其整體部分(即如果90.0等於90),那麼只打印整體部分,否則打印浮子。

#include <iostream> 
#include <math.h> 

using namespace std; 

void printFloat(float num) { 

    // convert num to properly rounded decimal with 1 decimal place 
    num = floor(num*10 + .5)/10; 

    // if the float equals the whole number, only show the whole number 
    if (num == (int)num) 
     cout << (int)num << endl; 
    else 
     cout << num << endl; 
} 

int main() { 
    float num1 = 90.0; 
    float num2 = 90; 
    float num3 = 90.00001; 
    float num4 = 95.7; 
    float num5 = 95.74; 
    float num6 = 95.75; 

    printFloat(num1); // prints 90 
    printFloat(num2); // prints 90 
    printFloat(num3); // prints 90 
    printFloat(num4); // prints 95.7 
    printFloat(num5); // prints 95.7 
    printFloat(num6); // prints 95.8 
} 
+1

'if(num ==(int)num)cout <<(int)num;否則cout << num;'更短。沒有必要減去得到的小數部分 –

+0

謝謝@LưuVĩnhPhúc - 我已更新我的答案,以反映您的更有效的建議。 – amallard