我刚刚开始使用 c/c++,并且经常遇到此错误。有时我只需在控制台中输入 c ,程序就会继续正常运行。但其他时候则不会,就像这段代码的情况一样。
我正在尝试创建一个简单的计时器/秒表,显示程序开始时经过的秒数。我试图根据变量是 1 还是 0 来控制它的打开或关闭状态。
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
int onoff = 1;
if (onoff == 1)
{
int timex = 0;
while (onoff < 1)
{
timex++;
printf("time: %d", timex);
sleep(1000);
}
}
else if (onoff == 0)
{
char timex[] = "off";
printf("the timer is %s", timex);
}
return 0;
}
也许我只需要弄清楚如何调试?如果是这样,我可以在哪里学习如何有效地调试吗?
最佳答案
使用 bool 变量 true
/false
、开/关或任意两个状态变量,这使您的程序更易于阅读。另外,重命名您的变量。
int main()
{
bool timer_on = true;
if (timer_on)
{
int timex = 0;
while (timer_on)
{
++timex;
cout << "time: " << timex << "\n"; // Since you supplied the C++ tag.
sleep(10000); // This is a platform or RTOS specific function.
}
}
else if (timer_off)
{
cout << "The timer is " << timex << "\n";
}
return 0;
}
一个问题是您定义 timex
if
的 then 部分内语句,并且 else
内的代码无法访问该语句部分。
您错过了决赛else
条款给您的if-else if
梯子。也许您想要类似的东西:
else
{
if (!timer_on)
{
}
}
或者也许是内心的if
不是必需的,因为代码将在 else
中执行语句如果timer_on是false
。
关于c++ - C++ 中的 11db 错误; Xcode。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18342526/