Loops 素数与否c++;cpp
问题2。自然数及其和 编写一个程序: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
- 要求用户输入一个整数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*的所有自然数;
库特