2017-10-24 21 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を評価します。 sum関数をループ内に置くと、それが破られると、ループ内のすべての情報がダンプされ、合計値が廃止されます。ループ内でsum関数を実現する別の方法があるが、ループの外側で一度だけ印刷する方法があるのだろうかと思う。

外部で抽出できるループ内の情報を削除しない他のループはありますか?

+0

ループは、範囲外のコードは、スコープ内で宣言変数にアクセスできないことを意味し、スコープされています。おそらくあなたがしたいことは、 'int sum = 0'のように、ループの外で宣言された変数を1つ持ち、それをループ内でそれに応じて更新することです。 – drglove

答えて

1

スコープ内で宣言された変数は、スコープ外ではアクセスできず、次の反復でも継承されません。

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何を説明したいですか?投稿された質問を読むと、ユーザーは2つの整数を連続して3回入力でき、プログラムは昇順で入力された数字を並べ替え、入力されたすべての整数を加算する合計変数を持ちます最後にすべての整数の和を出力します。 – Mronfire

+0

@Stefanあなたは正しいです。私はいくつかのコメントと詳細な説明を追加する必要があります。更新されます。 – Mronfire

+0

ありがとう、それはより多くの人々が負担するのに役立ちます。 – Stefan

関連する問題