Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Does someone know how to make a program that displays if a number is a perfect number?

Hi, I need to create a program that will display if a number is a perfect number or not. We need to use a boolean to determine if its perfect or not. Heere is what I have, but it's not working correctly.It displays that all numbers are perfect.Can someone help me find the problem?

#include <iostream>

#include <cmath>

using namespace std;

int main ()

{

//Prompt user to enter number and declare variables.

int n, sum = 0, f;

cout << "Please enter a number." << endl;

cin >> n;

while (n < 0)

{

cout << "Please enter a number." << endl;

cin >> n;

}

//Declare a boolean variable and additional variables as needed.Use rule to determine if it's a perfect number.

bool result;

for( f = 1; f <= n/2; f++)

if ( n % f == 0)

sum += f;

if ( sum == n)

result = true;

else

result = false;

//Use boolean variable to display results.

if (result = true)

cout << "The number " << n << " is a perfect number." << endl;

else if (result = false)

cout << "The number " << n << " is not a perfect number." << endl;

//Return that all is ok.

return 0;

}

1 Answer

Relevance
  • nicefx
    Lv 5
    10 years ago

    result doesn't have initial value, set the initial value

    you can NOT use = in conditional expression, you must use ==

    i hope it's help

Still have questions? Get your answers by asking now.