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;
}