for循环添加整数

for-Loop to add integers

本文关键字:整数 添加 循环 for      更新时间:2023-10-16

使用说明如下:


编写程序,接受键盘输入的整数,计算从1到该整数的所有整数的和。例如,如果输入7,则会计算出1 + 2 + 3 + 4 + 5 + 6 + 7的总和。使用while或for循环来执行计算。计算出总和后,打印出结果。注意:如果你输入一个大的整数,你将无法得到正确的结果。


我不明白的是如何将所有的整数加在一起。如有任何帮助,我将不胜感激。

//preprocessor directives

int main ()
{
//declare and initialize variables
    int n, i;
    int total;

//user input
    cout << "Enter an integer: ";
    cin >> n;

//compute sum of all integers from 1 to n
    total=0;
    for (i = 1; i <= n; i++)
    cout << i;

return 0;
}

您可以使用+=运算符进行添加:

for (i = 1; i <= n; i++)
    total += i;
cout << total;

注意这是total = total + i的缩写