gpt4 book ai didi

c++ - For 循环不递增或 while 循环不失败测试

转载 作者:搜寻专家 更新时间:2023-10-30 23:58:48 27 4
gpt4 key购买 nike

我有这部分代码应该找到给定范围内所有整数的 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;

}

最佳答案

current_number % 2 == 0 对于所有 current_number = 0, 2, 4, 6, ... 都是真的。

发生这种情况时,您将 current_number 设置为 current_number/2。因此,当 current_number 为 2 时,您将其设置为1,然后你递增它 (++current_number),然后它又是 2 (!= 1),所以你将输入 while循环,然后因为 2 % 2 = 0 你会再次将它设置为 1.. 依此类推.. :_(

生活小贴士:调试您的代码,这会节省时间、精力,有时还省钱。

关于c++ - For 循环不递增或 while 循环不失败测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18851223/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com