判断一个数是完美数还是素数
问题是: “编写一个函数来判断一个数是素数还是完全数。”
到目前为止,我已经首先完成了完美的部分,这就是我所拥有的:
#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;
}
但是,此代码似乎存在错误。 我看过这本书,但没有提到这个话题。 我想获得有关如何修复此代码的建议。
谢谢!
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.
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这不会调用
perfectNumber
函数;它声明了一个名为perfectNumber
且类型为bool
的局部变量,并使用转换为bool
类型的number
值对其进行初始化。为了调用
perfectNumber
函数,您需要使用以下内容:或:
另请注意:如果您要从流中读取输入(例如
cin>> number
),您必须检查以确保从流中提取值成功。现在,如果您输入asdf
,提取将会失败,并且number
将保持未初始化状态。检查提取是否成功的最佳方法就是测试流的状态:您可以在
basic_ios
上标志的语义。您还应该查阅一本优秀的入门级 C++ 书籍了解更多信息流使用最佳实践。This does not call the
perfectNumber
function; it declares a local variable namedperfectNumber
of typebool
and initializes it with the value ofnumber
converted to typebool
.In order to call the
perfectNumber
function, you need to use something along the lines of:or:
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 inasdf
, the extraction would fail andnumber
would be left uninitialized. The best way to check whether an extraction succeeds is simply to test the state of the stream: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.