Multiplication of the next number

I am trying to write a program that multiplies the input number by 2, and then multiplies this answer by 2 in a loop, however I can not get my program to multiply the second number, here is my code.

int main() {

    int number;

    cout << "Enter a number: ";
    cin >> number;

    while (true) {
        int multiply = number * 2;
        cout << "Answer: " << multiply << endl;
    }  
} 

How do I get this program to multiply a number that was previously multiplied? Thanks in advance!

+4
source share
4 answers

You keep “propagating” the same value over and over.

To achieve your goal, you need to save your result in "multiply", then * 2 of this variable. Something like that:

int multiply = number * 2;

while (true) {
    cout << "Answer: " << multiply << endl;
    multiply = multiply * 2;

}  

EDIT: A more elegant way to do this is using recursive functions. You can find a useful example here .

+3
source

:

while (true) {
    number = number * 2; // The same !
    cout << "Answer: " << number << endl;
}

, : int (2 ^ 31 - 1), max 30 .

+6

Use it

   int multiply = number;

    while (true) {

        multiply = multiply *2;
        cout << "Answer: " << multi << endl;
    }
+1
source

numberhas the same value for each iteration. You want to multiply multiplyby two each time, not number.

The first iteration is a special case, so you need to figure out how to initialize multiplyit to work.

+1
source

Source: https://habr.com/ru/post/1584886/


All Articles