-7
#include <iostream>
using namespace std;
int main()
{
char ch;
int n;
do {
cout << "Enter a number:";
cin >> n;
if (n % 2 == 0)
cout << "The number is even.\n";
else
cout << "The number is odd.\n";
bool prime;
for (int i = 2; i < n; ++i) {
if (n % i == 0)
prime = true;
}
if (prime) {
cout << "The number is not prime.";
}
else
cout << "The number is prime.";
cout << "Do you want to continue?[y/n]";
cin >> ch;
} while (ch == 'y' || ch == 'Y');
}
如果循环进入if(prime)一次,那么它永远不会进入else。 如果输入3,则循环的第一次运行将输出素数。然后在下一个如果输入4,则显示不是素数,但在此之后,只要输入任何质数,它就不显示素数。这个C++代码有什么问题?
你正在打破if子句中的循环。 – Carcigenicate
''如果prime:print(“你的数字不是素数)'没有多大意义 – Carcigenicate
欢迎来到Stack Overflow!听起来好像你可能需要学习如何使用调试器来遍历你的代码。好的调试器,你可以逐行执行你的程序,看看它与你期望的有什么不同,如果你要做任何编程,这是一个必不可少的工具。 ://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver