如何解决质数是否为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;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。