C++ 如何使用带I=I+的while循环打印前25个off整数的平方根;1而不是i=i+;2.

C++ 如何使用带I=I+的while循环打印前25个off整数的平方根;1而不是i=i+;2.,c++,while-loop,C++,While Loop,当我试图解决这个问题时,我编写了以下代码: int x = 1; while(x%2 != 0 && x <= 50) { //x%2 != 0 defines odd integers and x<=50 gives the first 25 cout << pow(x,0.5) << endl; x = x + 1; } intx=1; 虽然(x%2!=0&&xwhile在条件为true时执行。在第二次迭代中x

当我试图解决这个问题时,我编写了以下代码:

int x = 1;

while(x%2 != 0 && x <= 50) {      //x%2 != 0 defines odd integers and x<=50 gives the first 25
    cout << pow(x,0.5) << endl;
    x = x + 1;
}
intx=1;

虽然(x%2!=0&&xwhile
在条件为
true
时执行。在第二次迭代中
x==2
,因此条件
x%2!=0
变为
false
,因此
x%2!=0&&x在while内放置一个if以检查while条件是否为奇数,while条件应该是
问自己,val是什么当
x
为2时,条件
x%2!=0
的ue?您还可以使用
x
0
迭代到
24
并计算
pow(2*x+1,0.5)
。这样的循环与您的第二个代码相同。啊,这是有意义的@Cheers和hth,因为它是假的,整个条件被终止。谢谢如果您想保留
i=i+1
,那么您需要从
while
条件中删除
x%2!=0
。正如问题下面的注释中所建议的,将条件保留为de>x
int x = 1;

while(x%2 != 0 && x <= 50) {
    cout << pow(x,0.5) << endl;
    x = x + 2;
}