2012-06-12 21 views
2

我已經在我的C++程序中編寫了下面的代碼,但接近尾聲時,我需要計算x1/SumOfIntegers的值。我是一個初學者,我非常感謝任何能夠幫助我找出答案的小數結果的人。我一直使用2作爲我所有的整數輸入,所以x1 = 2SumOfIntegers = 10。因此x1/SumOfIntegers應該等於.2,但我始終得到1作爲輸出。有人可以幫幫我嗎?如何從兩個整數輸入產生一個十進制結果?

#include <iostream> 
#include "graphics.h" 
#define  _USE_MATH_DEFINES 
#include "math.h" 

using namespace std; 

int main() 
{ 

    double x1; 
    double x2; 
    double x3; 
    double x4; 
    double x5; 
    double SumOfIntegers; 
    const double Radius = 250; 
    double CircumferenceOfCircle; 
    double x1PercentOfTotal; 

    cout << 
     "You will be prompted to enter five integers for a pie chart \n"; 

    cout << "Enter integer 1: "; 
    cin >> x1; 

    cout << "Enter integer 2: "; 
    cin >> x2; 

    cout << "Enter integer 3: "; 
    cin >> x3; 

    cout << "Enter integer 4: "; 
    cin >> x4; 

    cout << "Enter integer 5: "; 
    cin >> x5; 

    cout << "Sum of integers: " << x1 + x2 + x3 + x4 + x5 << endl; 
    cin >> SumOfIntegers; 

    cout << "Circumference of Circle: " << 2 * (M_PI) * Radius << endl; 
    cin >> CircumferenceOfCircle; 

    cout << "x1 Percentage of Total " << (double)(x1)/
     (double)(SumOfIntegers) << endl; 
    cin >> x1PercentOfTotal; 

    return 0; 
} 

回答

1

你忘了計算SumOfIntegers值:

cout << "Sum of integers: " << x1 + x2 + x3 + x4 + x5 << endl; 
cin >> SumOfIntegers; 

你問用戶的總和類型和用戶往往非常糟糕的數據輸入。我建議你店鋪你自己的價值。 (我也建議繼續這惱人前等待用戶輸入。)

試試這個:

SumOfIntegers = x1 + x2 + x3 + x4 + x5; 
cout << "Sum of integers: " << SumOfIntegers << endl; 

(需特別注意,我已經刪除了cin >> SumOfIntegers

要查看具體是我在說什麼,改變運行之間的一個值:

$ echo "1 2 3 4 5 6 8" | ./foo 
You will be prompted to enter five integers for a pie chart 
Enter integer 1: Enter integer 2: Enter integer 3: Enter integer 4: Enter integer 5: Sum of integers: 15 
Circumference of Circle: 1570.8 
x1 Percentage of Total 0.166667 
$ echo "1 2 3 4 5 100 7" | ./foo 
You will be prompted to enter five integers for a pie chart 
Enter integer 1: Enter integer 2: Enter integer 3: Enter integer 4: Enter integer 5: Sum of integers: 15 
Circumference of Circle: 1570.8 
x1 Percentage of Total 0.01 

更改它從6100給出了不同的值 - 0.166667 vs 0.01

+0

謝謝!你能解釋爲什麼刪除cin >> SumOfIntegers解決了我的問題嗎?我是一個初學者,這是我寫的第一個程序。 – princessofsly5

+0

'cin >> SumOfIntegers' _overwrites_存儲的值與您在鍵盤中輸入的任意數字。 :) – sarnold

0

由於如何劃分運算符在C++中工作(不要問爲什麼,它是愚蠢的,但它就是這樣),當每個數字是一個整數時,它會把它看作奇怪的。如果您在其中一個數字的末尾實施.0,它將起作用。

例如:的

2.0而不是2

沒有安裝這臺機器上的Visual Studio,所以我無法驗證,如果X1 + 0.0將工作或沒有,但一些嘗試。

也可以計算總和而不是輸入它。

P.S.你不需要做鑄件加倍。因爲他們已經是雙打了,所以你的投注翻倍到了兩倍,並沒有達到什麼,而是浪費了時鐘週期。只要x1/SumOfIntegers將工作。

+0

通常是一個很好的捕獲,但是這些變量都被聲明爲'double',儘管經常被稱爲_integers_。 – sarnold

+0

啊是的,再次查看代碼後,我看到他們都是雙打,而不是一個int /雙組合。 –

相關問題