循环代码错误C ++?

时间:2016-03-21 02:34:45

标签: c++

这是来自C ++编程书的练习题。这个循环代码存在缺陷。我相信很多人会立即得到答案。我猜是使用前缀增量运算符。

      int x = 0; 
      while (x)
      {
        ++x;
       cout << x << endl;
      }

5 个答案:

答案 0 :(得分:1)

不,它的x=0; 您需要将x分配给正数(如x=1)以使循环运行,因为x=0的计算结果为false,因此循环不会运行。

答案 1 :(得分:0)

如果 x = 0 ,while循环将评估为false,并且while循环的主体将永远不会被执行,因为 x 将不会被更改并始终保持0

什么都不会输出,程序将以0的返回码退出,不能解决输出不足的问题。

答案 2 :(得分:0)

while循环根本不会执行,因为0被视为false

while(false){
//will not execute; since (x=0 == false)
}
//skips above code and execute this directly.

如果你想在循环内部运行代码,你可以给出一个真正的值,如x = 1;

while(true){
//will execute (since x=1 === true)
}

答案 3 :(得分:0)

while(1)相当于while(x == 0)while(0)相当于while(x)

语义”是“”运行时...而变量“ x ”包含 0 所以如果它直接添加到条件中,因为它是 0 = false

x == 0 ,如果x == 0则返回true。

...

return (x == 0);

答案 4 :(得分:0)

参考:https://www.tutorialcup.com/cplusplus/while-loop.htm

while(x)被评估为while(x!= 0),因此不会向控制台输出任何内容。即它与:

相同
#include "stdafx.h"
#include <iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{


    int x = 0;
    while (x != 0) 
    {
        ++x;
        cout << x << endl;

    }

    return 0;
}