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!
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.