决定一个数是完全数还是素数 [英] deciding if a number is perfect or prime
问题描述
问题是:编写一个函数来判断一个数是质数还是完全数."
the problem is : "Write a function to find out if a number is a prime or perfect number."
到目前为止,我已经完成了完美的部分,这就是我所拥有的:
so far i have worked on the perfect part first and this is what i have:
#include <iostream>
using namespace std;
bool perfectNumber(int);
int main()
{
int number;
cout<<"Please enter number:\n";
cin>>number;
bool perfectNumber(number);
return 0;
}
bool perfectNumber(int number)
{
int i;
int sum=0;
for(i=1;i<=number/2;i++)
{
if(number%i==0)
{
sum+=i;
}
}
if (sum==number)
return i;
else
return 0;
}
然而,这段代码似乎有错误.我看过这本书,但没有谈到这个话题.我想获得有关如何修复此代码的建议.
HOWEVER, there seems to be errors on this code. I have looked over the book but nothing talks about this topic. i would like to get advice on how to fix this code.
谢谢!
推荐答案
bool perfectNumber(number);
这不会调用perfectNumber
函数;它声明了一个名为 perfectNumber
的 bool
类型的局部变量,并用转换为 bool
类型的 number
的值来初始化它.
This does not call the perfectNumber
function; it declares a local variable named perfectNumber
of type bool
and initializes it with the value of number
converted to type bool
.
为了调用 perfectNumber
函数,您需要使用以下内容:
In order to call the perfectNumber
function, you need to use something along the lines of:
bool result = perfectNumber(number);
或:
bool result(perfectNumber(number));
另外一点:如果您要从流中读取输入(例如 cin>>number
),您必须检查以确保从流中提取值成功.现在,如果您输入 asdf
,提取将失败并且 number
将保持未初始化状态.检查提取是否成功的最好方法是简单地测试流的状态:
On another note: if you are going to read input from a stream (e.g. cin>>number
), you must check to be sure that the extraction of the value from the stream succeeded. As it is now, if you typed in asdf
, the extraction would fail and number
would be left uninitialized. The best way to check whether an extraction succeeds is simply to test the state of the stream:
if (cin >> number) {
bool result = perfectNumber(number);
}
else {
// input operation failed; handle the error as appropriate
}
您可以在 Semantics ofbasic_ios
上的标志.您还应该查阅一本优秀的入门级 C++ 书籍以了解更多信息流式使用最佳做法.
You can learn more about how the stream error states are set and reset in Semantics of flags on basic_ios
. You should also consult a good, introductory-level C++ book for more stream-use best practices.
这篇关于决定一个数是完全数还是素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!