C++ problems with division

279 Views Asked by At

I need to make a program in C++ in which I insert a number 'n' that's with 4 digits and it's a simple number, in the console and the console is showing me the multiplication of the certain number with 4 digits which I first needed to write. I tried to write (n/!2) in order to make the program execute only if the number can't divide by 2 and the console showed "main.cpp:22:36: warning: division by zero [-Wdiv-by-zero]". I've tried removing (n /! 2) and the code got executed without a problem. I will be glad if someone can tell me how can I fix it.

#include <bits/stdc++.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int getProduct(int n)
{
    int product = 1;
    while (n != 0) {
        product = product * (n % 10);
        n = n / 10;
    }
    return product;
}
int main()
{
    int n;
    cout << "insert n ";
    cin >> n;
    if (n >= 1000 && n <= 9999 && n /! 2) {
        cout << (getProduct(n));
    }
}
4

There are 4 best solutions below

0
Yksisarvinen On

You are looking for modulo operation. Modulo (the remainder from division) is equal to zero if number is divisible by the other one and non-zero otherwise.

if (n >=1000 && n <= 9999 && (n % 2) != 0)
0
a.koptan On

tried to write (n/!2) in order to make the program execute only if the number can't divide by 2

n / !2

This evaluates to n / 0. which triggers your warning.

To check if n is odd, you should do this instead:

n % 2 != 0
0
Ted Lyngmo On

In the calculation n / !2 You effectively do n / 0.

! is short for not, not 2 is a boolean expression where 2 (anything but 0) is true.

not true is false.

false is promoted to an int in the calculation and false there becomes 0.

Solution: Use n % 2 != 0 or n & 1 to check for odd numbers.

0
BHAVUK GARG On

! operator have higher precedence than / , So your expression becomes

=> n/(!2) => n/0

Instead you shoud use (n%2==0) to check for even number.