C++ 我的质数检查器出了什么问题?
我创建了一个质数检查程序,它检查用户输入的质数与否 它很容易检测到非素数,但当我们输入素数时,它崩溃了 我想我知道为什么,但不知道如何纠正它们 以下是我的节目:C++ 我的质数检查器出了什么问题?,c++,if-statement,primes,C++,If Statement,Primes,我创建了一个质数检查程序,它检查用户输入的质数与否 它很容易检测到非素数,但当我们输入素数时,它崩溃了 我想我知道为什么,但不知道如何纠正它们 以下是我的节目: #include "stdafx.h" #include <iostream> #include<iomanip> #include <cmath> using namespace std; float Asker() { float n; cin >> n;
#include "stdafx.h"
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
Remainder(n, x + 1 > n);
/*
Here is the PROBLEM
*/
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n = Asker();
int r = Remainder(n, 2);
if (r == 1)
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
main();
return 0;
}
#包括“stdafx.h”
#包括
#包括
#包括
使用名称空间std;
浮动询问器()
{
浮动n;
cin>>n;
返回n;
}
整数余数(整数n,整数x)
{
int q=n%x;
如果(q==0)
返回1;
其他的
余数(n,x+1>n);
/*
问题就在这里
*/
返回0;
}
int main()
{
cout首先,对于小于等于n-1的所有数字,您不必检查模:检查小于等于sqrt(n)
的模就足够了。其次,如果要检查的下一个除数大于sqrt(n)
,您应该从函数返回0。下面是更正的余数函数
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
{
if(x+1 > std::sqrt(n)) return 0;
else return Remainder(n, x + 1);
}
}
最后,最好将main
和Asker
中的n
类型从float
更改为int
,并且Asker
的返回类型也应该是int
这并不是一个关于质数检查器在焦点上有什么问题的详尽列表-只是一种快速修复它的方法。本质上,这样的质数检查器不应该使用递归-只需迭代从2到sqrt(n)
的所有潜在因子就可以更好地回答您的问题“我的质数检查器出了什么问题?”很多事情都错了:
- 不要在main中调用
main()
。递归不是这样做的
int余数(int n,int x)
用一个float
(cast丢失)调用它,然后用一个bool
:余数(n,x+1>n);
- 您的
asker
不需要是浮点数
关于main
中的递归,有两个原因:
- 使用此配置,您将得到一个无止境的循环
-
ISO-C++禁止函数的地址::主'< /p>
/#包括“stdafx.h”//这是无效的标题。
#包括
#包括
#包括
使用名称空间std;
浮动询问器()
{
浮动n;
cin>>n;
返回n;
}
整数余数(整数n,整数x)
{
int q=n%x;
如果(q==0&&n>2)//'2'必须被排除。
//否则,可以设置2%2==0
//“2”作为非素数,这是错误的
返回1;
否则,如果(x+1 n)'x+1>n'是无效参数。
*/
其他的
返回0;
}
int main()
{
不能输入参数
在这之后,为什么要在main函数中调用main()?
你的算法需要一些技巧,我已经在评论中添加并解释过了
但是你应该知道,检查素数的最短方法是检查n%x==0直到x为什么不尝试一个迭代的解决方案,它更容易实现,更清晰我相信你的代码甚至没有编译。我接受你的其他观点,但为什么我不在main中调用main()。@JebinMatthew我给出的答案有问题吗?
//#include "stdafx.h" //This is an invalid header.
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0 && n>2 )//'2' have to be excluded.
//otherwise 2%2==0 can set
//'2' as a non prime which is wrong
return 1;
else if(x+1<n)
Remainder(n, x + 1);
/*
Here was the PROBLEM
Remainder(n, x + 1 > n) 'x + 1 > n ' is an invalid paramrter.
*/
else
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n=Asker();
int r=1; //It is essential to initialize r to 1
if(n!=1) //Have to exclude '1'. Otherwise
//It will assign '1' as prime which is wrong
r = Remainder(n, 2);
if (r == 1 )
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
//main(); //Why are you calling main again?
return 0;
}