bool函数 [英] bool function for prime numbers
问题描述
我有以下代码用于使用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;
}
}
它适用于所有数字 我如何修改代码,使它也适用于这些值? 此外,还有一条错误消息 感谢。 到以下 I have the following code for checking whether the first 20 positive numbers are prime using a bool function. It works for all numbers How could I modify the code so it would work for these values too? Also there is an error message Thanks. Modify your prime function to the following The 这篇关于bool函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 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
传递给函数时,它不会进入循环,所以退出没有显式返回任何东西,这可能导致未定义的行为)。一般来说,您希望在任何条件结构之外都有返回指令。#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;
}
}
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)
."Control may reach end of non-void function"
. Why is this?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;
}
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.