0

here is the code I am having an issue with:

int printDividers(int x)
{
    for (int j=0; j<x+1; j++)
    {
        if (x%j==0) cout << j << ", ";
    }
}

int main()
{
    int z;
    cout << "Enter a number and the program will print out it's dividors:" << endl;
    cin >> z;
    printDividers(z);

    return 0;
}

After entering your number it says main.exe stopped working. I haven't figured out why, I can't spot the error in the code.

dhein
  • 6,431
  • 4
  • 42
  • 74
Blank空白
  • 117
  • 8

3 Answers3

4

When i==0, we will run the test if (x%0 == 0) which isn't a valid statement because it attempt to divide by 0. Hence, your program will might crash. Its behavior is undefined

dhein
  • 6,431
  • 4
  • 42
  • 74
Danh
  • 5,916
  • 7
  • 30
  • 45
4

You're out of luck, you are attempting to compute % 0 in your for loop. Along with integral division by zero, the behaviour on doing this is undefined:

The C++03 Standard states in §5.6/4,

[...] If the second operand of / or % is zero the behavior is undefined; [...]

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

What is x % 0? (Answer: Undefined Behaviour) This is what causes your run-time error.

Change to this:

for (int j=1; j<x+1; j++)

http://ideone.com/K5vSxt

Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175