bool函数 [英] bool function for prime numbers

查看:132
本文介绍了bool函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码用于使用bool函数检查前20个正数是否为素数。

  #include< ; iostream> 
#include< cmath>
using namespace std;

bool prime(int);
/ *
函数来评估正整数是否为素数(true)
或不是素数(false)
* /
int main()
{
for(int x = 1; x <= 20; x ++)
{
cout< x < a prime?(1 yes,0 no)
<< prime(x)<< endl
}
return 0;
}

bool prime(int x)
{
for(int i = 2; i <= sqrt(x); i ++)

if((x%i)!= 0)
return true;
else
return false;
}
}

它适用于所有数字 1到20 除了 2和3 ,其中输出为 0 ,而不是 1 。我想我知道为什么。对于 x = 2和3 中没有 i c> c>循环,使得 i <= sqrt(2) i <= sqrt(3)。 >

我如何修改代码,使它也适用于这些值?



此外,还有一条错误消息控制可能到达非void函数结束。为什么是这样?



感谢。

解决方案

到以下

  bool prime(int x)
{
if(x< 2)return假;
for(int i = 2; i <= sqrt(x); i ++){
if((x%i)== 0)return false;
}
return true;
}

控制可能到达非void函数结束错误消息告诉您,在所有情况下,您的素数函数不返回(当您将 1 传递给函数时,它不会进入循环,所以退出没有显式返回任何东西,这可能导致未定义的行为)。一般来说,您希望在任何条件结构之外都有返回指令。


I have the following code for checking whether the first 20 positive numbers are prime using a bool function.

#include <iostream>
#include <cmath>
using namespace std;

bool prime(int);
/* 
function to evaluate whether a positive integer is prime (true)
or not prime (false)
*/
int main()
{
    for(int x=1; x<=20; x++)
    {
        cout <<  x << " a prime ? (1 yes, 0 no) "
             << prime(x) << endl;
    }
    return 0;
}

bool prime(int x)
{
    for(int i=2; i<= sqrt(x); i++)
    {
        if ((x%i) != 0)
            return true;
        else
            return false;
    }
}

It works for all numbers 1 to 20 apart from 2 and 3 where the output is 0 instead of 1. I think I know why. For x = 2 and 3 there is no i in the for loop such that i<=sqrt(2) or i<=sqrt(3).

How could I modify the code so it would work for these values too?

Also there is an error message "Control may reach end of non-void function". Why is this?

Thanks.

解决方案

Modify your prime function to the following

bool prime(int x)
{
  if (x < 2) return false;
  for(int i=2; i<= sqrt(x); i++) {
    if ((x%i) == 0) return false;
  }
  return true;
}

The Control may reach end of non-void function error message tells you that your prime function does not return in all cases (When you pass 1 to your function, it does not go in the for loop, and so exit without explicitly returning anything, which could lead to undefined-behavior). In general, you want to have a return instruction outside of any conditionnal structure.

这篇关于bool函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆