gpt4 book ai didi

c++ - 如何找出为什么我的程序一直有无限循环?

转载 作者:行者123 更新时间:2023-11-30 03:13:57 25 4
gpt4 key购买 nike

我似乎找不到我的代码有什么问题,我试图在答案等于 0 时结束循环,但它一直在无限循环中。

#include <iostream>
int main() {
using namespace std;
int x, remainder;
cout << "please enter a positive integer number: " << endl;
string tab;
tab = '\t';
cin >> x;
remainder = x % 2;

do{
while ( x % 2 != 0)
{
cout << x << " is odd" << tab << "Subtract 1" << tab << " Half of " << x - 1 << " is " << x / 2;
x = (x - 1) / 2;
cout << endl;

}

while (x % 2 == 0)
{
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
x = x / 2;
cout << endl;
}

}
while (x >= 0);
}

最佳答案

本质上,您的代码中存在两个问题,这两个问题本身都会使您的循环无休止地运行。

从外部开始并向内工作:(外部)while 循环结束时的测试将始终为“true”,因为您有 while (x >= 0) ;因此,即使 x 变为零(它会如此),循环仍将继续运行! (而且,一旦 x 为零,它将保持为零!)

其次,两个“内部”while 循环根本不应该是循环!您希望一个或另一个“ block ”在每个主循环中只运行一次 - 所以使用 if ... else 结构。

以下是您的代码的更正版本:

#include <iostream>

int main() {
// using namespace std; // Generally, not good practice (and frowned-upon here on SO)
using std::cin; using std::cout; using std::endl; // Use only those you want to!
using std::string;
int x, remainder;
cout << "please enter a positive integer number: " << endl;
string tab;
tab = '\t';
cin >> x;
remainder = x % 2;

do {
if (x % 2 != 0)
{
cout << x << " is odd" << tab << "Subtract 1" << tab << " Half of " << x - 1 << " is " << x / 2;
x = (x - 1) / 2;
cout << endl;
}
else // if (x % 2 == 0) ... but we don't need to test this again.
{
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
x = x / 2;
cout << endl;
}
} while (x > 0); // You run forever if you have x >= 0!
return 0;
}

还有一些其他的东西可以更改以使代码更“高效”,但在我们开始编辑 BPC(最佳可能代码)之前,我会让您仔细阅读 MNC(最小必要更改) )!

编辑:好的,由于来自评论的“同行压力”😊,我现在将放入一个建议 BPC:

#include <iostream>

int main() {
using std::cin; using std::cout; using std::endl; // Use only those you want to!
int x;// , remainder; // "remainder" is never used, so we can discard it!
cout << "Please enter a positive integer number: " << endl;
cin >> x; // Not critical, but I like to put such a cin right after the prompting cout.
std::string tab{ "\t" }; // Let's initialise more directly!
do {
// As there is only one line (now) inside each if/else block, we can leave out the {} ...
if (x % 2 != 0)
cout << x << " is odd" << tab << "Subtract 1" << tab << "Half of " << x - 1 << " is " << x / 2;
else
cout << x << " is even" << tab << "Subtract 0" << tab << "Half of " << x << " is " << x / 2;
// We can put the following two line outside the tests, as they will be the same in both cases:
x = x / 2; // When x is ODD, this will give the SAME answer as x = (x - 1)/2 (as you noticed in your first cout)
cout << endl;
} while (x > 0); // You run forever if you have x >= 0!
return 0;
}

关于c++ - 如何找出为什么我的程序一直有无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58315952/

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