質問

I have this section of code that's supposed to find the Collatz sequence of all integers in a given range, defined by user input. The problem is that in the for loop, current_number never gets incremented, or in the inner while loop, current_number != 1 never fails. What am I missing?

while (lower != 0 && upper != 0) {
    cout << "Lower bound (integer): ";
    cin >> lower;
    cout << "Upper bound (integer): ";
    cin >> upper;
    if (lower == 0 || upper == 0)
        return 0;
    for (current_number = lower; current_number <= upper;
        ++current_number) {
            //cout << current_number << endl;
            counter = 0;
            sequence = sequence + to_string(current_number) + ", ";
            while (current_number != 1) {
                if (current_number % 2 == 0) {
                    current_number = current_number / 2;
                    sequence = sequence + to_string(current_number) + ", ";
                }
                else {
                    current_number = current_number * 3 + 1;
                    sequence = sequence + to_string(current_number) + ", ";
                }
                cout << current_number << endl;
                ++counter;
            }
            //if (counter > longest) {
            //  longest = counter;
            //  the_longest_seed = current_number;
            //}
    }
    cout << sequence << endl;

}
役に立ちましたか?

解決 2

Next to the other error, you are also using current_number to iterate over the input-range and you're changing it to output your Collatz sequence. You should change a copy of current_number.

他のヒント

current_number % 2 == 0 is true for all current_number = 0, 2, 4, 6, ....

When this happens, you set current_number to be current_number / 2.. So when current_number is 2, you're setting it to 1, then you increment it (++current_number), then it's 2 again (!= 1), so you'll enter the while loop, then because 2 % 2 = 0 you'll set it to 1 again.. And so on.. :_(

Tip for life: Debug your code, it'll save time, efforts and sometimes money too.

Concerning never-failing loop. If current_number != 1 and it is not 2 (if it is, the other guy has answered), it goes into the while loop and never ends, because...

Let's say it is 3:

3 % 2 != 0, so it becomes 10,

10 % 2 == 0, so it becomes 5,

5 %2 != 0, so it becomes 16

...

Never fails.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top