2017-10-24 2 views
0

for 문에서 사용자가 입력 한 숫자의 합계를 계산하고 for 루프가 완료된 후이를 인쇄하는 방법에 대한 통찰력을 찾으십시오.for 루프 내의 SUM 함수, C++

지금까지 나는이 코드를 가지고 :

//this code will sort 2 numbers then print them in ascending order and 
before exiting, add them all together 
// then average them 

#include <iostream> 
using namespace std; 

int main(int,char**) { 

int n, m, z, sort1, sort2; 

for (n=0;n<3;n++){ 
    cout << " enter two integers (n n): "; 
    cin >> m; 
    cin >> z; 

    if (m>z){ 
     sort1 = z; 
     sort2 = m; 
    } 
    else{ 
     sort1 = m; 
     sort2 = z; 
    } 
    cout << sort1 << sort2 << endl; 
    } 
int sum = m+z; 
int sum2 = m+z+sum; 
float sum3= m+z+sum2; 
cout << " sum of all numbers entered: " << sum << endl; 
cout << " average of the numberes entered: " << sum3 /6 << endl; 
} 

그래서 내가 가지고있는 SUM 함수가 잘못된 것을 알고를, 그것은 단지 사용자가 아닌 다른 사람에 의해 마지막으로 입력 한 m + Z를 평가합니다. 합계 함수를 루프에 넣으면 브레이크가 걸리면 루프 내의 모든 정보가 덤프되어 합계 값이 더 이상 사용되지 않게됩니다. 루프 내에서 합계 기능을 수행하는 다른 방법이 있지만 루프 외부에서 한 번만 인쇄하는 것이 아닌지 궁금합니다.

외부에서 추출 할 수있는 루프 내의 정보를 삭제하지 않는 다른 루프가 있습니까?

+0

루프 범위 내에 선언 변수에 액세스 할 수없는 범위 밖에 해당 코드를 의미하는 범위가된다. 당신이하고 싶은 것은 'int sum = 0'과 같이 하나의 변수를 루프 밖에서 선언 한 다음 루프 내에서 적절히 업데이트하는 것입니다. – drglove

답변

1

C++의 모든 루프는 범위가 지정됩니다. 즉, 범위 내에서 선언 된 변수는 범위 외부에서 액세스 할 수 없으며 다음 반복에도 적용되지 않습니다.

int sum = 0; // declare sum outside of loop 
for(int n = 0; 0 < 3; n++) 
{ 
    int m, z; // These will be reset every iteration of the for loop 
    cout << " enter two integers (n n): "; 
    cin >> m; 
    cin >> z; 

    /* 
     Sort and print goes here... 
    */ 

    sum += m + z; 
} 
std::cout << "The sum: " << sum <<std::endl; 
+0

복합 할당은 내가 찾던, 고마워! @Chris Mc –

1
#include<iostream> 
using namespace std; 

int main() 
{ 

    int total = 0, i, j, sort1, sort2; 

    //this For-Loop will loop three times, every time getting two new 
    //integer from the user 

    for (int c = 0; c < 3; c++) { 
     cout << "Enter two integers (n n): "; 
     cin >> i; 
     cin >> j; 

    //This will compare if first number is bigger than the second one. If it 
    //is, then second number is the smallest 
     if (i > j) { 
      sort1 = j; 
      sort2 = i; 
     } 
     else { 
      sort1 = i; 
      sort2 = j; 
     } 

     cout << "The numbers are: " << sort1 << " and " << sort2 << endl; 

    //This statement will add into the variable total, the sum of both numbers entered before doing another loop around 
     total += i + j; 
    } 

    cout << "The sum of all integers entered is: " << total << endl; 

    system("pause"); 

    return 0; 
} 
+0

@Stefan 설명해 주시겠습니까? 게시 된 질문을 읽으면 사용자가 연속으로 두 번 정수를 입력 할 수있는 솔루션을 제공했으며 프로그램은 오름차순으로 입력 된 숫자를 정렬하고 입력 된 모든 정수를 추가하는 총 변수를 갖습니다. 마지막에는 모든 정수의 합을 출력합니다. – Mronfire

+0

@ 스 테판 당신 말이 맞아요. 나는 약간의 코멘트와 더 많은 설명을 추가해야했다. 업데이트됩니다. – Mronfire

+0

고마워요, 그러면 사람들이 더 많이 도움이 될 것입니다. – Stefan