为什么 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?
#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以双倍返回答案。
我写了双平方,因为对于某些数字,当您将其分配给整数变量时,它的平方可能会被截断/四舍五入。有关详细信息,请参阅此问题。
相关文章:
- 在C++中如何在没有pow的情况下进行基础计算
- 理解GCC中的std::pow实现
- 子例程,不使用 pow,并带有参数和返回
- 整数溢出,最大值为 pow(10,19)
- 在 while 循环中使用 pow() 函数 C++
- 在C++不使用 POW 的情况下处理负指数
- C++ 中 pow() 函数的输出没有给出准确的答案
- 没有匹配'pow'功能
- 为什么 while ((i <= 9) && square == pow(i, 2)) { cou
- Arduino Pow() 和 Armstrong 数问题
- C++在不使用pow或循环的情况下计算一个数字的幂
- 让constexpr在OSX上的C++17中使用pow
- Why (int)pow(2, 32) == -2147483648
- 错误:"int pow(double,int)"与上一个声明int pov(double a,int
- Pow 在 C++ 中无法按预期工作
- C++使用负矢量大小计算的 pow 行为
- 在C++中使用 pow() 时出错
- 如何修复 E2015 "ambiguity between pow(double,double) and pow(float,int)"
- constexpr exp, log, pow
- NAN 使用 pow 评估指数时,但如果我迭代,答案正确?