首页 > 解决方案 > 试图找到一个数字的日志,但由于某种原因它不起作用

问题描述

我正在尝试编写一个解决日志功能的程序。首先,我只是让它可以计算具有整数答案的日志(例如,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;
    
}

标签: c++recursion

解决方案


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

推荐阅读