我已经尝试解决一个小时了,这非常令人沮丧,我无法理解下一个循环为什么不验证自己的原因
while(p>1) {
p--;
if (pow(n, contor) == p) {
contor2++;
}
}
完整的代码是
#include <iostream>
#include <cmath>
int main()
{
int n, p, resetP;
float contor = 0;
float contor2 = 0;
n = 3;
p = 100;
resetP = p;
while (p > 1)
{
contor++;
p = p / n;
}
p = resetP;
while (p > 1)
{
p--;
if (pow(n, contor) == p)
contor2++;
}
std::cout << contor2;
}
我在这里尝试做的是验证
if(pow(3, 4)==81
,但似乎不起作用。我将p
设置为从100到0逐一。当它达到81时,它只是越过了它,就像它只是不验证if
和我的contor2
保持完全相同(为0)一样。我已经学习C++超过6个月了,但这是我第一次真正坚持使用某些东西。
最佳答案
我用x86和x64的msvsc 19和g++运行了几次您的代码,它的工作方式如异常(exception)并打印1
当p
达到81并且将counter2加1时进入if语句
这是我尝试的代码
#include <iostream>
#include <cmath>
int main() {
int n, p, saveP = 0, resetP;
float contor = 0;
float contor2 = 0;
n = 3;
p = 100;
resetP = p;
while (p > 1) {
contor++;
p = p / n;
}
p = resetP;
while (p > 1) {
p--;
if (pow(n, contor) == p)
contor2++;
}
std::cout << contor2;
}
检查您的编译器设置(也许您未在编译要编辑的cpp文件)
并检查语法错误(如if语句中的作用域)
我不知道您的整个代码是什么,但是在这里将
counter
和counter2
声明为int,并将p
声明为float是比较好的
关于c++ - 为什么不能在 `pow`循环中验证 `while`函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61646676/