2016-07-15 15 views
0

合計する整数の数を入力できるプログラムを作成しましたが、取得できるようになりましたが、ユーザーが再び行くと前の合計に加算され続けます新しい整数を再起動して追加する必要があります。数値は集計を続けますが、集計は停止しません

#include "stdafx.h" 
#include <iostream> 
#include <string> 

using namespace std; 
// ================ 

int main() { 
    // Declared Variables 
    int num; 
    int sum; 
    int total = 0; 
    char ans = 'y'; 

    // =========== 

    using namespace std; 
    // While loop which allows user to go again. 
    while (ans == 'y' || ans == 'Y') 
    { 
     // Input for adding any number of integers 
     cout << "How many integer values would you like to sum? "; 
     cin >> num; 
     cout << endl; 
     // ========= 

     // For Loop allows to add integers 
     for (int i = 0; i < num; i++) 
     { 
      cout << "Enter an integer value: "; 
      cin >> sum; 
      total += sum; 


     } // End for loop 
     // ============== 

     // Prints out the sum of the numbers 
     cout << "The sum is " << total << endl; 
     cout << endl; 

     // Asks the user if they want to go again 
     cout << "Would you like to go again (y/n)? "; 
     cin >> ans; 
     cout << endl; 

     if (ans != 'y') 
     { 
      cout << "Bye..." << endl; 
     }// End If statement 
     // ================ 

    }// End while loop 
    // ============== 

    cout << endl; 
    return 0; 
} // Function main() 
// ================= 
+0

リセットする必要があります – drescherjm

+0

コードをステップ実行しながらデバッガを使用してエラーを検出するのは古典的なケースです。スタックオーバーフローに関する質問?非常に議論の余地がある! –

答えて

4

whileループ内を移動この行を:あなたのwhileループの開始時に

while (ans == 'y' || ans == 'Y') 
{ 
    int total = 0; 

    // Input for adding any number of integers 
    cout << "How many integer values would you like to sum? "; 
    ... 
+0

Upvoted、これはここ1位で有効な答えでした。私は実際に受け入れられた答えをロールバックするように誘惑されています。醜い[FGITWフォーム](http://stackoverflow.com/posts/38385989/revisions)です。 –

0

int total = 0; 

すなわち

total = 0; 

がここにはるかに短いです、あなたのコードの改良されたバージョン。

int main() 
{ 
    char ans; 

    do { 
     int n, sum = 0;   

     std::cout << "Enter the number of numbers\n"; 
     std::cin >> n; 
     while (--n >= 0) { 
      int x; 
      std::cout << "Number? "; 
      std::cin >> x; 

      sum += x; 
     } 
     std::cout << "Sum is " << sum << "\nGo again?(y/n)\n"; 
     std::cin >> ans; 
    } while (ans == 'y' || ans == 'Y'); 

    std::cout << "Bye\n"; 
    return 0; 
} 
+0

私は 'total = 0'を意味すると思います。 – smarx

+0

固定@smarx – stackptr

+0

@smarxセミコラがないか、キーボードの人に何か問題がありますか? –

関連する問題