0

代码;

# include <iostream>
# include <windows.h>
using namespace std;

int main () {
    int var1 = 1;
    int var2 = 1;
    bool while1 = true;
    int x = 0;

    while (x < 999) {
        x = x+var1;
        x = x+var2;
        cout << x << " Is the current value of x, how much would you like to add to it?\n";
        Sleep(1000);
        while (while1) {
            int var3;
            cin>> var3;
            if (var3 > 100) {
                cout << "Too large, between 10 and 100\n";
                while1 = true;
            } 
            else if (var3 < 10) {
                cout << "Too small, between 10 and 100\n";
                while1 = true;
            }
            else{
                cout << "Adding " << var3 << " to " << x << "\n";
                x = x + var3;
                cout << "x is now " << x << "\n";
                while1 = false;
            }
        }
    }
}

现在,问题在于它在第一次循环后完全跳过第二个 while 语句并继续将 var1 和 var2 添加到 x。

这里有什么问题?

4

1 回答 1

4

您永远不会将变量重置为true. 把它放在外循环的某个地方,就像while (while1) {在行之前:

while1 = true;

事实上,当您在部件中设置它时,它就一直是假的else。或者,将其设置为无限循环(for (;;)while (true))并仅使用break;而不是,然后完全删除其他两个中的while1 = false;提及。while1

此外,您的外部循环可以替换为for循环:

for (int x = 0; x < 999;)

这甚至可以消除对这两个x = x + var1; x = x + var2;语句的需要。我将按照var1and保留它var2

for (int x = -var1 - var2; x < 999; x += var1 + var2)

var1而且var2永远不会改变,所以如果它们有一些实际意义,我建议制作它们const并将它们重命名为传达该意义的东西。否则,只是说x = x + 2,或更短,x += 2;

<windows.h>最后,如果你使用 C++11,你可以通过使用标准的 sleep 函数来摆脱依赖:

#include <thread>
#include <chrono>
...
std::this_thread::sleep_for(std::chrono::seconds(1));
于 2013-05-16T03:14:30.870 回答