问题描述
第二季度。自然数及其和。
编写一个程序,该程序:
- 要求用户输入整数 n ;
- 在屏幕上打印所有小于 n 的自然数;
- 计算所有这些自然数的总和。
我已经完成了大部分操作,但是不知道如何在错误编号后自动让程序重新开始循环。
我的代码:
#include <iostream>
using namespace std;
int main() {
int n,i,sum = 0;
//Ask the user to input an integer
cout << "Input an integer: ";
cin >> n;
if ( n > 0){
for (i = 1 ; n > i ; i++ )
{
//Calculate sum of differences
sum += i;
//Prints all the natural numbers that are less than the *n* on the screen;
cout << i << ",";
}
}
else
{
cout << "Place a positive integer" <<endl;
}
//printed sum
cout << "\nthe sum of these numbers is: " << sum << endl;
return 0;
}
解决方法
尝试以下操作:
while(cin >> n) {
if ( n > 0){
for (i = 1 ; n > i ; i++ )
{
//Calculate sum of differences
sum += i;
//Prints all the natural numbers that are less than the *n* on the screen;
cout << i << ",";
}
}
else
{
cout << "Place a positive integer" <<endl;
}
}