我不确定我是否应该在这里问或程序员,但我一直在试图弄清楚为什么这个程序不能工作,虽然我发现了一些错误,但它仍然返回“x 不是质数”,即使它是。
#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i < b; i++) {
//If the user input has no remainder then it cannot be a prime and the loop can stop (break)
if (a % i == 0) {
return(0);
break;
}
//Other wise if the user input does have a remainder and is the last of the loop, return true (it is a prime)
else if ((a % i != 0) && (i == a -1)) {
return (1);
break;
}
}
}
int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
cout << user << " is a prime number.";
}
else {
cout << user<< " is not a prime number.";
}
cout << "\n\nPress enter to exit...";
getchar();
getchar();
return 0;
}
对不起,如果这太本地化了(在这种情况下,你能建议我应该在哪里问这样的具体问题吗?)
我应该补充一点,我对 C++(和一般编程)非常陌生
这只是为了测试功能和控制。