2014-10-31 46 views
-1

我有一個做while循環創建,它幾乎正是我想要的,但其中的一部分重複比我想要的更多。下面是代碼:do-while循環的一部分重複的次數超過了它應該的次數。我該如何解決?

#include <iostream> 
#include <iomanip> 

using namespace std; 

int main() // none of the above is included in the pdf version of this file but I put it in anyway. 
{ 
int count = -1, number = 1, product = 1; 
do 
{ 
    ++count; 
    product = product * number; 
    cout << "Enter an integer number to be included in the product " 
<< endl << "or enter 0 to end the input: "; // I put endl in this weird position just because I found it more readable lined up like this that is all. 
    cin >> number; 
} 
while (number != 0); 

if (count > 0) 
{ 
    cout << endl << "The product is " << product << "." << endl; 
} 
} 

的問題是,「輸入一個整數被包含在產品或輸入0結束輸入I輸入號碼後重復它仍然給了我正確的答案。但是當我不想要它的時候,cout仍然會重複,我試着修復了很多不同的方法(注意:我對編程非常陌生),但是每一個都會讓程序不再起作用,或者不能在第一次修復它

該評論對象是我的老師,非常抱歉,如果這不是實際的代碼,這是我第一次在這裏發表任何東西

+0

適用於我 - 您使用什麼輸入?你看到了什麼輸出?請注意,如果輸入任何無效(即不是整數),您的程序將永久循環。 – 2014-10-31 04:20:53

+0

爲什麼整個「輸入0結束輸入」的東西,如果你不想重複? – 2014-10-31 05:56:38

回答

0

輸出「輸入要包含在產品中的整數或輸入0結束輸入:」將繼續顯示,直到用戶輸入0爲止。因爲它是DO while循環,它將運行一次,然後檢查每次輸入。如果輸入不是0,它將再次運行。

如果你想用戶輸入的輸入的最大數量,你可以改變這一行:
while(number != 0);

這樣:
while (number != 0 && count < {max subtracted by one});

和變化{最大值由一個減去到你所需的最大輸入數減1(因爲你的計數器從負數開始)。

例如,如果你想有一個最大的10個號碼,你會改變線路:
while (number != 0 && count < 9);

然而,應該指出的是,因爲你評估產品之前,先接受輸入時,您輸入的最後一個數字將不會包含在評估中。因此,您可能想要將do while循環內的代碼更改爲:

++count; 
cout << "Enter an integer number to be included in the product " 
<< endl << "or enter 0 to end the input: "; // I put endl in this weird position just because I found it more readable lined up like this that is all. 

cin >> number; 

if (number != 0) //This prevents multiplication by 0 when they type a 0 
    product = product * number; 
相關問題