为什么 while ((i <= 9) && square == pow(i, 2)) { cou

Why isn't while ((i <= 9) && square == pow(i, 2)) { cout << i << square; i++; printing out as I want it to?

本文关键字:cou pow while lt 为什么 square      更新时间:2023-10-16
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int i = 0;
int square = 0;
// Write a while loop here:
while ((i <= 9) && square == pow(i, 2)) {
cout << i << square;
i++;

}
}
//Why is this not printing out 
/* 0   0
1   1
2   4
3   9
4   16
5   25
6   36
7   49
8   64
9   81
*/

/有人可以向我彻底解释为什么这个 while 循环无法打印出这个数字序列。
我不明白为什么这只打印出 00 而不是那个数字列表。有人可以向我解释为什么这个 while 循环无法正常工作吗?
/

你可能想做:

while (i <= 9) {
square = pow(i, 2);
cout << i << square;
i++;
}

或:

while (i <= 9 && (square = pow(i, 2))) {
cout << i << square;
i++;
}

否则,一旦square == pow(i, 2)为假,循环就结束了,你似乎想分配平方而不是比较它

原因是您不会在每次迭代中更新"平方"值,并且它始终等于零,因此您的 while 循环立即以 i = 1 终止,因为平方 = 0 且 pow(i,2( = 1 。您应该注意到,square == pow(i,2)条件不会将右侧值分配给平方变量。它只比较它们。从您想要的输出中,我知道您可能需要这样的东西:

i = 0;
while (i <= 9) {
cout << i << "     " << pow(i, 2);
i++;
}

你应该这样做:

// For version
double square;
for (int i = 0 ; i <= 9 ; i++) {
square = pow(i, 2);
cout << i <<" "<< square <<"n";
}
//While version
double square;
int i = 0;
while (i <= 9) {
square = pow(i, 2);
cout << i <<" "<< square <<"n";
i++;
}

Pow双倍返回答案。

我写了平方,因为对于某些数字,当您将其分配给整数变量时,它的平方可能会被截断/四舍五入。有关详细信息,请参阅此问题。