C ++ integer division by zero

I need to write a program that enters a number and displays the highest divisor, and then the senior divisor of the divisor, etc., until it reaches a prime. But I continue: "Unhandled exception at 0x00eb1504 in the primefinder.exe file: 0xC0000094: integer division by zero."

I assume that his "num% i" calls it, but "i" cannot be zero since its "num / 2".

#include <iostream>

using namespace std;

int main(){
    unsigned int i=666, num;
    cout << "Enter number";
    cin >> num;
    while(i>1){
        i = num/2;
        while(num % i == 0){
            i--;
        }
        cout << i << endl;
        num=i;
    }
    cin.get();
    return 0;
}
+3
source share
3 answers

As the ogo mentions in his comment, 1/2 (and 0/2) will be zero due to integer math.

To avoid dividing by 0 here, change cin >> num;to:

do
{
    cin >> num;
} while (num <= 1);

This will continue until you enter a real number.

: , while i > 0 && num % i == 0.

+1

i , num % i . ? , 2 . :

    i = num/2; // i is now (2 / 2) = 1
    while(num % i == 0){ // 2 % 1 = 0, so the loop continues
        i--; // i is now zero, so the next loop iteration will cause a division by zero!
    }

, :

while(i > 0 && num % i == 0)

, i .

+1
int main(){
    unsigned int i=666, num;
    cout << "Enter number";
    cin >> num;
    while(i>1){
        i = num/2;

666, i=num/2

, " , .." .

0

All Articles