简体   繁体   中英

While loop in function not terminating

I know the answer is probably very simple, but I've nearly exhausted myself trying everything I know in c++, which isn't much. The first function works, to my knowledge, I just can't get the loop to terminate.

#include <iostream>
#include <cstdlib>

using namespace std;

unsigned int reverseInt(unsigned int num)
{
    unsigned int rem, reverse;

    while(num > 0)
    {
        rem = num % 10;
        reverse = reverse * 10 + rem;
        num /= 10;
    }
    return reverse;
}

unsigned int generateSequence(unsigned int num, ostream& out)
{
    unsigned int k = 0;

    while(num != 1)
    {
        num = num + 4;
        num = reverseInt(num);
        k++;
        out  << ", " << num;
    }
    out << endl;
    return k;
}

There are few problems with the code

  1. reverse variable is not getting initialized even once in function reverseInt .

  2. num variable is not getting reduced to 1 and loop will not terminate.

While analyzing your logic it looks like you have a finite loop with higher outcome as number of digits increase.

Your application reduces number of digit when sum of 4 reaches a digit ending with 6, But since you have unsigned int type which has higher range.

Application will get timeout if you go reaches threshold number of digits which generate more outcome for compiler to exit, say 5 digit number as threshold Eg: 11111.

Your issue is mainly that reverse is not initialized, on at least clang and gcc this means reverse will be initialized with its maximum value (2^64).

This means your loop never finishes as num just gets bigger and bigger and bigger, you will have a lot of integer overflows but since num is assigned from the return value of reverse , num will never hit 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM