2011-09-15 77 views
-3

可能重複:
Equation not working correctly in C++
Help with POW function in C++c + +浮動瓦爾四捨五入

在此代碼:

//Samuel LaManna 
//Program 1 (intrest rate) 
/*Variables: 
Principal=P 
Interest Rate=R 
Times Compounded=T 
Savings=S 
Interest=I */ 

#include <iostream>  //Input/output 
#include <cmath>  //Math Functions 

using namespace std; 

int main() 
{ 
    float P, R, T, S, I;                  //Declaring Variables 
    cout<<endl; 
    cout<<"Interest Earned Calculator";              //Prints program title 
    cout<<endl; 
    cout<<endl; 
    cout<<"Please enter the Principal Value: "; 
    cin >> P; 
    cout<<endl; 
    cout<<endl; 
    cout<<"Please enter the Interest Rate (in decimal form): "; 
    cin >> R; 
    cout<<endl; 
    cout<<endl; 
    cout<<"Please enter the Number of times the interest is compounded in a year: "; 
    cin >> T; 
    cout<<endl; 
    cout<<endl; 
    S=pow(1+R/T,T)*P; //Equation to find Savings 
    I=S-P;    //Equation to find interest in $ 
    cout<<"Interest Rate: " << R*100 <<"%" ; 
    cout<<endl; 
    cout<<endl; 
    cout<<"Times Compounded: " << T; 
    cout<<endl; 
    cout<<endl; 
    cout<<"Principal: $" << P; 
    cout<<endl; 
    cout<<endl; 
    cout<<"Interest: $" << I; 
    cout<<endl; 
    cout<<endl; 
    cout<<"Ammount in Savings: $" << S; 
    cout<<endl; 
    cout<<endl; 
    return 0; 
} 

有沒有一種方法,使最終輸出的數字輪到2位小數位即使它們是0?

+2

[你有什麼試過?](http://mattgemmell.com/2008/12/08/what-have-you-tried) –

+0

看看[setprecision](http://www.cplusplus。 com/reference/iostream/manipulators/setprecision /) –

+0

我甚至不知道要開始,我是一名學生。 –

回答

5

我們假設我對cout的功能一無所知。因爲我對cout一無所知,所以我爲「C++ cout」做了一個搜索引擎查詢。我點擊第一頁such as this MSDN doucmentation的其中一個鏈接。根據該頁面,我發現cout是一個ostream,它輸出到標準輸出。所以我們來看看ostreamso conveniently provided in the MSDN documentation。在ostream頁面上,有a link called "iostream Programming"。這看起來很有希望,所以讓我們點擊它。

在「iostream編程」頁面上有a link called "Output Streams"。再次,這看起來很有希望。畢竟,我們正在向屏幕輸出一些東西,所以讓我們來看看。在該頁面上,有a link called "Using Insertion Operators and Controlling Format"。聽起來我們正在接近。

你瞧,我偶然看到一個顯示「如何控制格式」的頁面。該頁面上有一個名爲「Precision」的部分,描述了功能setprecision() and setiosflags() complete with code examples。根據文件,或許它可能解決你的問題。

我採取的上述過程通常是由互聯網成員通俗地稱爲"RTFM"。這是一種非常有用的技術,可以自己獲取信息,並可以利用您的優勢來領先於同行。

+0

Silico想要說些什麼(以迂迴和幽默的方式)是查找setprecision和setwidth以及iomanip頭文件。以防萬一它太鈍了:-) – paxdiablo

+0

是的,如果我知道用戶總是要輸入具有相同位置值的數字,那將是完美的。對於校長來說,他們可以輸入1,000美元或1,000,000美元。如果我設置精度爲他們輸入1,000,那麼它會削減數字,如果他們輸入1,000,000 –

+0

我想我知道了,如果我在setprecision之前使用fixed,它只會計算小數點後的數字 –