for循环添加整数
for-Loop to add integers
使用说明如下:
编写程序,接受键盘输入的整数,计算从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
的缩写
相关文章:
- 添加存储在向量中的大整数的函数出现问题
- 当我们从/tp地址中添加/减去一个整数时会发生什么
- 如何在 sqlite3 中的表中添加整数列表
- 使用指针将 ASCII 值添加到整数
- 我正在尝试制作一个程序,在添加 n 天(整数)后告诉一个人什么是一天(例如星期一等)
- C++向数组添加元素并调整数组大小
- 野牛/flex:计算器将双精度值解释为整数,所以我添加了 YYSTYPE 双精度 #define 但我有多个编译错误
- 斯塔克,堆栈,也可以在底部和顶部添加整数
- 通过在带有 C++ 的列表中添加连续元素来计算新的整数列表
- 计算机使用什么方法添加无符号整数
- 如何拆分整数并将所有内容添加到数组中?
- 调整数组大小并添加元素 C++
- 将整数添加到数组值而无需调用它的最安全方法
- 在C++中使用 cin 同时将整数添加到数组中
- 将整数添加到字符
- Qt:QTableWidget 将整数添加到表中
- 将多个整数添加到一个向量索引? 'Cout'不起作用
- 如何将多个整数添加到字符数组中,然后将它们拉出
- 无法将整数添加到标准::复杂<double>
- 为股票类的整数添加分配内存