我正在尝试编写一个程序,它会告诉您输入的数字是否为素数,并将 1 到 100 之间的所有素数写入一个文件并显示这些数字。这是我到目前为止所拥有的,但我迷路了。
bool isPrime(int);
int _tmain(int argc, _TCHAR* argv[])
{
int num, answer, choice, i, numb=1;
do
{
cout<< "Enter a number and I will tell you if it is prime or not."<<endl;
cin>> num;
if (isPrime(num))
cout<<num<<" is a prime number."<<endl;
else
cout<<num<< " is not a prime number."<<endl;
cout<<"Would you like the first 100 prime numbers displayed? (1 for yes and 2 for no)"<<endl;
cin>>choice;
if (choice == 1)
{
while(numb<=100)
{
i=2;
while(i<=numb)
{
if(num%i==0)
break;
i++;
}
if(i==num)
cout<<numb<<" is Prime"<<endl;
numb++;
}
}
else
{
cout<<"Would you like to run the program again? (1 for yes and 2 for no)"<<endl;
cin>>answer;
if (answer == 2)
{
exit(0);
}
}
while (answer == 1);
}
system("pause");
return 0;
}
bool isPrime (int number)
{
int i;
for (i=2; i<number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
最佳答案
真的觉得你想多了。您已经完成了困难的部分,即编写 isprime 函数。
显示数字很简单,只需编写一个 for 循环遍历数字并检查哪些是素数,如果特定数字是素数则将其打印到屏幕。
然后只需将写入文件的内容添加到循环中,以打印到屏幕上的那些数字。
关于c++ - 如何编写一个程序来显示一个数是否为质数,并可以显示文件中从 1 到 100 的质数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5275946/