【发布时间】:2015-11-15 00:00:20
【问题描述】:
我想制作一个程序,要求用户输入一个介于 1 和 100 之间的整数“n”,并有一个输入验证循环。然后程序将计算前'n'个素数并打印它们。所以我想出了如何计算质数并显示它们,每行 10 个数字,所有这些都在 main 函数中。我要做的是有一个名为 isPrime() 的函数,它接受一个整数,如果它是素数则返回 true,否则返回 false。我不知道该怎么做。这是我为函数 main() 编写的代码。
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number;
int count = 0;
cout << "Enter an integer between 1 and 100: ";
cin >> number;
while (number < 0 || number > 100)
{
cout << "Invalid number." << endl;
cout << "Enter an integer between 1 and 100: ";
cin >> number;
}
cout << "The first " << number << " primes: \n" << endl;
for (int i = 2; number > 0; ++i)
{
bool isPrime = true;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
count++;
--number;
cout << setw(5) << i;
if (count % 10 == 0)
cout << endl;
}
}
cout << endl;
system("pause");
return 0;
}
任何帮助都是好的,在此先感谢。
【问题讨论】: