我的质数检查器怎么了?
Whats wrong with my Prime number Checker?
我创建了一个素数检查程序,检查用户输入的数字是否为素数。
它很容易检测到非素数,但是当我们输入素数时,它崩溃了!
我想我知道为什么,但不知道如何纠正它们…
这是我的程序:
#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;
}
假设,当我输入7,我知道,它检查到6,那么它应该崩溃!(由于x + 1> n的条件)。我不知道如何在else条件失败时返回0
回答你的问题"我的质数检查器出了什么问题?"很多事情都是错的:
- 不要调用main中的
main()
。递归不是这样的 -
int Remainder(int n, int x)
,您使用float
(缺少cast)然后使用bool
调用它:Remainder(n, x + 1 > n);
- 你的
asker
不需要是一个浮动
关于main
内的递归,有两个原因:
- 使用这个配置你将得到一个无限循环;
-
ISO c++禁止接受函数'::main'的地址
//#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;
}
- 你的第一个错误是" #include "stdafx.h"。你从哪弄到这个头的?在int Remainder(int n, int x)函数中,你使用了递归并发送了一个无效的语法"Remainder(n, x + 1> n)"。"。你不能在参数中使用x+1>n这样的语法。
- 之后,为什么你在main函数内调用main() ?你的算法需要一些改进我已经在评论中添加并解释过了。
但是你应该知道检验质数的最短方法是检验n%x==0直到x<=square_root(n)。
首先,您不必检查n-1
之前的所有数字的模量:检查sqrt(n)
之前的模量就足够了。其次,如果要检查的下一个除数大于sqrt(n)
,则应该从函数返回0。以下是修正后的Remainder
函数。
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)
的所有可能的因数会更简洁。
相关文章:
- 不断收到相同的错误...怎么了?C++
- 编译器没有显示错误,但我没有得到任何输出.怎么了?
- qsort 不适用于我的 impl 中的浮点类型。怎么了?
- 在C++中表现不佳.怎么了?
- 我的程序怎么了?(C )
- 这里怎么了?单位转换器
- 错误:未定义对 .. 的引用.怎么了
- 我试图编写一个代码来查找一个单词是否是回文,但它不起作用。怎么了?
- 我在C++文件中的简单代码块上有 2 个错误。错误 C2059:语法错误:"?"。第二智能感知:预期表达式。怎么了?
- 我的代码怎么了?带有QT的原始输入API
- 使用 cin.get() 似乎没有读取我期望的字符。怎么了?
- 当其中一个字符串来自cin时,无法比较两个字符串.这里怎么了
- "5"怎么了?纸上一切都很好
- 我的cout怎么了
- C++:腹肌怎么了
- Qt OpenGL with Widgets:怎么了?
- 程序为某些条目提供了错误的输出!怎么了?
- 自动和复制构造函数:怎么了?
- 怎么了???只有七行
- 我的质数检查器怎么了?