1

以下のコードを使用しましたが、番号が間違っていて、講師は for ループを使用したいと考えています。また、印刷する必要があります。

「n」から「n」の合計は「 」 (1 から 1 の合計は 1) 「n」から「n」の合計は「 」 (1 から 2 の合計は 3)

for ループを使用してみましたが、上記を出力するコードを正しく取得できないようです。道に迷いました!

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

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    const int NUM_LOOPS = 50;
    int count = 0;
    while (count < NUM_LOOPS)
    {
        cout << "Sum of 1 through " << count << " is " << (count * (++count)) / 2 << endl;
    }

    system("pause.exe");
    return 0;
}
4

4 に答える 4

3
for (int count = 1; count <= NUM_LOOPS; ++count)
{
    cout << "Sum of 1 through " << count << " is " 
         << (count * (count+1)) / 2 << endl;
}

おかしなインクリメントと数式を混ぜないでください。あなたのこれからの人生がもっと楽しくなりますように。

于 2013-09-18T14:49:58.890 に答える
1

すべての要約を計算するのは良い方法ではないと思います。現在、1 つの要約を維持するだけでよく、そのたびに新しい値を追加するだけです

複数の操作は、単一の追加よりも時間がかかるためです。

const int NUM_LOOPS = 50;
int count = 0, sum = 0;

while ( count < NUM_LOOPS )
  cout << "Sum of 1 through " << count << " is " << (sum+=(++count)) << endl;
于 2013-09-18T15:54:21.337 に答える
0

私の例は1から10までです

    int sum=0;
    for (int i = 1; i < 11; i++) {
        for (int j = 1; j <= i; j++) {
             cout << j;
             sum=sum+j;
            if(j != i){
                  cout << " + ";                     
            }
        }
        cout << " = " << sum;  
        sum=0;
       cout <<"\n";
    } 

出力は次のとおりです。

1 = 1

1 + 2 = 3

1 + 2 + 3 = 6

1 + 2 + 3 + 4 = 10

1 + 2 + 3 + 4 + 5 = 15

1 + 2 + 3 + 4 + 5 + 6 = 21

1 + 2 + 3 + 4 + 5 + 6 + 7 = 28

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

于 2015-02-09T12:12:28.407 に答える