2016-07-15 1 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 루프 내부에이 라인 :

int total = 0; 

즉 :

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 form] (http://stackoverflow.com/posts/38385989/revisions). –

0

당신의 while 루프의 시작 부분에서 : 여기

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 고정 세미콜라가 없거나 키보드에 문제가 있습니까? –

관련 문제