Anshul Rai
Anshul Rai

Reputation: 782

Floating point exception even after checking if divided by zero

I started learning C++ recently and I am attempting to write a program where I take a given integer of any size as input, and then find the digits in this number that exactly divide the integer. The count of such digits is displayed as result.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
int n;   //Number of Integers to take as input
cin>>n;
vector<int> a;
for(int i=0;i<n;i++){
    long long val;
    cin>>val;
    a.push_back(val);
}
for(int i=0;i<n;i++){
    int k=1,count=0,r,q;
    r=a[i];
    q=a[i];
    while(k==1){
        q/=10;
        r=q%10;          
        if(a[i]%r==0 && r>=1)
            count++;
        if(q<10 && q>=1){
            if(a[i]%q==0)
                count++;
            k=0;
          }
        if(q==0)
            k=0;
    }
    cout<<count<<"\n";
}

return 0;
}

The above code works for integers WITHOUT the digit '0' but when I use any integer which has 0 as a digit, this is displayed:

Error Floating point exception (core dumped)

I've tried modifying the code by trying to skip the digit whenever 'r' or 'q' equates to '0' but nothing seems to be working. Any help/advice would be appreciated!

Upvotes: 0

Views: 96

Answers (1)

Wintermute
Wintermute

Reputation: 44063

When r is 0, this:

if(a[i]%r==0 && r>=1)

will not work because a[i]%r cannot be evaluated (modulo 0 would require division by 0 to be defined). It attempts to evaluate the division before r>=1 is checked. If you rearrange it like

if(r >= 1 && a[i] % r == 0)

then it should work because the && operator short-circuits out after r >= 1 has been determined to be false.

Upvotes: 2

Related Questions