我需要编写一个C ++程序,它显示从1到50的每个n的总和为1到n

时间:2013-09-18 14:46:14

标签: c++

我使用了以下代码,但我的数字不正确&我的教练宁愿使用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 个答案:

答案 0 :(得分:7)

使用for循环,它看起来像这样:

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

如果你愿意,你可以在while循环中编写它。

您的问题是您将count初始化为0而不是1。大概是为了处理你在长count中间修改cout的事实。对<<运算符的评估相对于彼此没有排序,并且您的代码表现出未定义的行为,正如此前已经多次讨论过的那样。

这样做的底线是,除了最简单的表达式之外,前后增量运算符都是危险的。谨慎使用。

答案 1 :(得分:3)

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

不要将有趣的增量与数学公式混合使用。你未来的生活会更快乐。

答案 2 :(得分: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;

答案 3 :(得分: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

相关问题