素数C++程序

Seb*_*hef 1 c++ primes

我不确定我是否应该问这里或程序员,但我一直在努力弄清楚为什么这个程序不会工作,虽然我发现了一些错误,它仍然会返回"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;
}
Run Code Online (Sandbox Code Playgroud)

对不起,如果这太局部化了(在这种情况下你能建议我应该问哪些具体问题吗?)

我应该补充一点,我对C++(以及一般的编程)非常陌生

这只是对功能和控制的测试.

Car*_*rum 5

i永远不能等于a - 1- 你只是去做b - 1. b存在a/2,这永远不会导致匹配.

这意味着返回1的循环结束条件永远不会成立.

如果是素数,则运行循环结束.这会导致未定义的行为,因为return那里没有语句.Clang发出警告,没有任何特殊标志:

example.cpp:22:1: warning: control may reach end of non-void function
      [-Wreturn-type]
}
^
1 warning generated.
Run Code Online (Sandbox Code Playgroud)

如果您的编译器没有警告您,则需要打开更多警告标志.例如,-Wall在使用GCC时添加会发出警告:

example.cpp: In function ‘bool primetest(int)’:
example.cpp:22: warning: control reaches end of non-void function
Run Code Online (Sandbox Code Playgroud)

总的来说,您的主要检查循环要比它需要的复杂得多.假设您只关心a大于或等于的值2:

bool primetest(int a)
{
    int b = sqrt(a); // only need to test up to the square root of the input

    for (int i = 2; i <= b; i++)
    {
        if (a % i == 0)
           return false;
   }

   // if the loop completed, a is prime
   return true;
}
Run Code Online (Sandbox Code Playgroud)

如果要处理所有int值,可以if (a < 2) return false;在开头添加一个值.