用C++,分别用whille, do—while,for语句,求不大于n(n从健盘输入)的素数之和
时间: 2024-10-12 16:07:26 浏览: 40
C语言与单机--循环do whille
在C++中,你可以使用while、do-while和for循环来计算小于等于用户输入的n的所有质数之和。以下是三种方法的示例代码:
1. 使用`while`循环:
```cpp
#include <iostream>
using namespace std;
bool isPrime(int num) {
if (num <= 1)
return false;
for (int i = 2; i * i <= num; ++i) {
if (num % i == 0)
return false;
}
return true;
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
int sum = 0;
int num = 2; // 从2开始,因为1不是质数
while (num <= n) {
if (isPrime(num)) {
sum += num;
}
num++;
}
cout << "Sum of primes less than or equal to " << n << ": " << sum << endl;
return 0;
}
```
2. 使用`do-while`循环:
```cpp
#include <iostream>
// ... (isPrime函数同上)
int main() {
int n, sum = 0, num = 2;
do {
if (isPrime(num)) {
sum += num;
}
num++;
} while (num <= n);
// ... (输出sum)
}
```
3. 使用`for`循环:
```cpp
#include <iostream>
// ... (isPrime函数同上)
int main() {
int n, sum = 0;
for (int num = 2; num <= n; ++num) {
if (isPrime(num)) {
sum += num;
}
}
cout << "Sum of primes less than or equal to " << n << ": " << sum << endl;
}
```
在这三个例子中,关键部分都是检查一个数是否为质数,然后累加到总和上,直到达到或超过给定的n值。
阅读全文