Search code examples
c++divide

Dividing a number in loop until it satisfies a condition = 0


I have to input a value in the program and keep dividing it by 4 until it reaches the number 0. But when I run it, it doesn't stop at 0, it keeps repeating 0 forever. What is wrong with the code?

#include <iostream>

using namespace std;

int main(){
    double input;
    cout << "Enter an Integer: ";
    cin >> input;
    cout << input << "/ 4 ";
    do
    {
        input = input / 4;
        if (input >= 0)
            cout <<" = "<< input << endl;
        cout <<input << " /4";
    }
    while ((input >= 0) || (input != 0));
    return 0;
}

Solution

  • Here are my three cents.:)

    #include <iostream>
    
    int main() 
    {
        const long long int DIVISOR = 4;
    
        while ( true )
        {
            std::cout << "Enter an Integer (0 - Exit): ";
    
            long long int n;
    
            if ( not ( std::cin >> n ) or ( n == 0 ) ) break;
    
            std::cout << std::endl;
    
            do
            {
                std::cout << n << " / " << DIVISOR;
                n /= DIVISOR;
                std::cout << " = " << n << std::endl;
    
            } while ( n );
    
            std::cout << std::endl;
        }
    
        return 0;
    }
    

    The program output might look like

    Enter an Integer (0 - Exit): 1000
    
    1000 / 4 = 250
    250 / 4 = 62
    62 / 4 = 15
    15 / 4 = 3
    3 / 4 = 0
    
    Enter an Integer (0 - Exit): 0