简体   繁体   English

质数的 Bool function 总是返回 true

[英]Bool function for prime number is returning true always

I am solving a simple problem for checking if a number is prime or not.我正在解决一个检查数字是否为素数的简单问题。 I tried using a simple approach but When I tried using bool it always print Yes .我尝试使用一种简单的方法,但是当我尝试使用bool时,它总是打印Yes What I am missing?我缺少什么?

#include<iostream>
bool isPrime(int);
using namespace std;

         // using bool 
    bool isPrime(int n)
    { 
        bool Prime;
         if( n==0 or n==1){     
             Prime=false;

         }
         else{
             for(int i=2;i<n;i++){
                 if(n%i==0){

                      Prime = false;
                      break;                  
                              }
             }
         }
       
    }

         




int main(){
    int n;
    cin>>n;  //7
    bool Prime = true;
   isPrime(n);
         if(Prime)
                         cout<<"Yes"<<endl;

         
         else
               cout<<"No"<<endl;

         
   
   return 0;
}

There are two variables named Prime in your code and they are not related in any way.您的代码中有两个名为Prime的变量,它们没有任何关系。 Each of them is a local variable of a different function. The local variables of a function are not visible outside that function.每一个都是一个不同的function的局部变量。一个function的局部变量在那个function之外是不可见的。

There are multiple ways to fix your code.有多种方法可以修复您的代码。 Your function is declared as returning a bool ( bool isPrime(int n) ) but it does not return anything.您的 function 被声明为返回 bool ( bool isPrime(int n) ) 但它不返回任何内容。 Let it return the promised value:让它返回承诺的值:

bool isPrime(int n)
{ 
  if (n <= 1) {     
    // Return early for the trivial cases
    return false;
  }

  // Normal cases
  for (int i = 2; i < n; i ++) {
    if (n % i == 0) {
      // Divisible by `i` => not prime
      return false;
    }
  }

  // Does not have dividers => prime
  return true;
}

Now using the function is easy:现在使用 function 很容易:

int main(){
  int n;
  cin >> n;
  
  if (isPrime(n)) {
    cout << "Yes" << endl;
  } else {
    cout << "No" << endl;
  }

  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM