质数是否为c ++ cpp

问题描述

第二季度。自然数及其和。

编写一个程序,该程序:

  • 要求用户输入整数 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;
  }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...