c++ - 试图找到一个数字的日志,但由于某种原因它不起作用
问题描述
我正在尝试编写一个解决日志功能的程序。首先,我只是让它可以计算具有整数答案的日志(例如,log 6 of 36 = 2)。我采用了递归路线,从逻辑上讲,它似乎非常可行,但在尝试实现它时,它不起作用。我没有收到任何语法错误,但正在发生的是我收到“未处理的异常”错误,我认为这是因为我采用了递归路线(出于某种原因无限循环?)。希望这是足够的信息来回答,谢谢!
int counter = 1;
void checkifDone(int initial, int base, int exponent);
int main() {
checkifDone(6, 6, 7776);
}
void checkifDone(int initial, int base, int exponent) {
base = initial * base;
counter++;
if (base < exponent) {
checkifDone(initial, base, exponent);
}
else if (base == exponent) {
cout << "Answer is " << counter << endl;
}
else
cout << "not a whole number answer" << endl;
}
解决方案
只要base != exponent
. else
永远不会调用分支(因为并if
涵盖else if
所有可能性)。
更简单的是使用 while 循环并检查小于:
void checkifDone(int base, int exponent) {
int count = 0;
int curr = 1;
while (base < exponent) {
curr *= base;
++count;
}
if (curr == exponent) {
std::cout << "Answer is " << count << std::endl;
} else {
std::cout << "not a perfect log" << std::endl;
}
}
推荐阅读
- php - laravel 数组用不同的 id 更新多行
- javascript - 有没有办法消除 Angular Js 中的这个错误?
- sql - 如何将数组传递给更新语句?
- visual-studio - OpenDDS 构建中的问题
- jprofiler - JProfiler 未检测到正在运行的 AdoptOpenJDK 11 openJ9
- angular - 如何防止 Ionic 应用程序中的 html 注入
- html - div中图像旁边的CSS文本
- python - 在将方法应用于python中的新列表后分配一个列表
- ssl - Openssl 访问器函数从不透明结构 X509_REQ 中检索 sig_alg
- python - build_absolute_uri 函数总是使用 http 协议生成 url