Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 素数与否c++;cpp_Loops_For Loop_While Loop_Do While - Fatal编程技术网

Loops 素数与否c++;cpp

Loops 素数与否c++;cpp,loops,for-loop,while-loop,do-while,Loops,For Loop,While Loop,Do While,问题2。自然数及其和 编写一个程序: 要求用户输入一个整数n 在屏幕上打印所有小于n的自然数 计算所有这些自然数的总和 我已经完成了大部分工作,但不知道如何让程序在输入错误的号码后再次启动循环,它会自动结束 我的代码: #include <iostream> using namespace std; int main() { int n, i, sum = 0; //Ask the user to input an integer cout &l

问题2。自然数及其和

编写一个程序:

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

}
#包括
使用名称空间std;
int main(){
int n,i,和=0;
//要求用户输入一个整数
cout>n;
如果(n>0){
对于(i=1;n>i;i++)
{
//计算差额之和
总和+=i;
//打印屏幕上小于*n*的所有自然数;
请尝试以下操作:

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;
  }
}
while(cin>>n){
如果(n>0){
对于(i=1;n>i;i++)
{
//计算差额之和
总和+=i;
//打印屏幕上小于*n*的所有自然数;
库特