Home > Software engineering >  Reversing a while loop
Reversing a while loop

Time:09-23

Reversing a while loop, I don't know if it's the correct way to ask the question, but come on. I have a code that converts any whole number to a two or three digit decimal. How? dividing the integer value by two until it is less than 10, counting in turn the times it divided it in the redo variable, thus we obtain the tenth: decimal = (integer, redo):

        int InitialInteger = 190;
        int Integer = InitialInteger;
        int redo = 0;
        while (Integer > 10)
        {
            Integer = Integer / 2;
            redo  ;
        }
        //Salida: 5,5

Now I want to get back the initial integer value ("reverse the loop") that is, multiply the integer part by 2 as many times as the decimal part indicates: Integer = (decimal1 * 2)^decimal2

        int decimal1 = Int16.Parse(Decimal.Split(',')[0]);
        int decimal2 = Int16.Parse(Decimal.Split(',')[1]);
        while (decimal2 > 0)
        {
            redo -= 1;
            InitialInteger  = decimal2 * 2;
        }
        //Salida: 60

but it doesn't work, it never returns the initial value! Any idea?

CodePudding user response:

Note that you have to set Integer as a float instead of as int for it to work.

Use this instead

int InitialInteger = 190;
float temp = InitialInteger;
int redo = 0;
while (temp > 10)
{
    temp= temp / 2;
    redo  ;
}

and then to reverse

while (redo > 0)
{
    temp = temp * 2;
    redo--;
}

At the end temp (or Integer as you called it!) is again 190

  • Related