Question

I am trying to write a code that finds perfect numbers lower than the user's input. Sample of correct output:

Enter a positive integer: 100
6 is a perfect number
28 is a perfect number
There are no more perfect numbers less than or equal to 100

But when I run my code, I get the error Floating point exception

and can not figure out why. What am I doing wrong?

Here is my code:

#include <iostream>

using namespace std;

bool isAFactor(int, int);

int main(){
    int x, y;
    int countOut, countIn;
    int userIn;
    int perfect = 0;

    cout << "Enter a positive integer: ";
    cin >> userIn;

    for(countOut = 0; countOut < userIn; countOut++){
        for(countIn = 1; countIn <= countOut; countIn++){
            if(isAFactor(countOut, countIn) == true){
                countOut = countOut + perfect;
            }
        }

        if(perfect == countOut){
            cout << perfect << " is a perfect number" << endl;
        }

        perfect++;
    }

    cout << "There are no more perfect numbers less than or equal to " << userIn << endl;

    return 0;
}


bool isAFactor(int inner, int outer){
    if(outer % inner == 0){
        return true;
    }

    else{
        return false;
    }
}
Was it helpful?

Solution 2

To clarify @Aki Suihkonen's comment, when performing: outer % inner If inner is zero, you will get a divide by zero error.

This can be traced backward by calling isAFactor(0, 1).
It is in your for loop in main.

The first parameter to isAFactor(countOut, countIn) is assigned in the outermost for loop: for (countOut = 0; ...

Notice the value you are initializing countOut with.

Edit 1:

Change your `isAFactor` function to:  

    if (inner == 0)
    {
       cerr << "Divide by zero.\n";
       cerr.flush();
       return 0;
    }
    if (outer % inner ...

Place a breakpoint at either cerr line above.
When the execution stops there, look at the Stack Trace. A good debugger will also allow you to examine the parameter / values at each point in the trace.

OTHER TIPS

The arguments are just swapped. You are calling the function as isAFactor(countOut, countIn) when you should be calling with isAFactor(countIn, countOut)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top