2

我有这部分代码应该找到给定范围内所有整数的 Collat​​z 序列,由用户输入定义。问题是在for循环中,current_number永远不会增加,或者在内部while循环中,current_number != 1永远不会失败。我错过了什么?

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;

}
4

3 回答 3

7

current_number % 2 == 0对所有人都是如此current_number = 0, 2, 4, 6, ...

发生这种情况时,您设置current_numbercurrent_number / 2.. 所以当current_number2 时,您将其设置为 1,然后将其递增 ( ++current_number),然后再次为 2 ( != 1),因此您将进入while循环,因为2 % 2 = 0您将再次将其设置为 1.. 等等.. :_(

生活提示:调试您的代码,它会节省时间、精力,有时还会节省金钱。

于 2013-09-17T13:35:46.853 回答
0

关于永不失败的循环。如果 current_number != 1 并且不是 2(如果是,则其他人已回答),它会进入 while 循环并且永远不会结束,因为...

假设它是3:

3 % 2 != 0,所以它变成了 10,

10 % 2 == 0,所以它变成了 5,

5 %2 != 0,所以变成 16

...

从未失败。

于 2013-09-17T13:36:22.890 回答
0

在另一个错误旁边,您还使用current_number迭代输入范围并将其更改为输出您的 Collat​​z 序列。您应该更改current_number.

于 2013-09-17T13:38:58.143 回答