c++ - C++ 中的幂函数

标签 c++

<分区>

我正在玩一个幂函数的实现:

#include <iostream>
using namespace std;

int pow(int b, int e)
{
  int result;

  if (e == -1 && b != 0)
  {
    cout << "b = " << 1/b << endl;
    return 1/b;
  }

  else if (b != 0 && e != 0)
  {
    //int e_int(int (e));
    bool e_bool(e < 0);
    e = (e_bool*-e + !e_bool*e);
    result = b = pow(b, -e_bool)*(b*!e_bool + +e_bool);
    cout << endl << "\"result\" = " << result << " " << e << endl;

    for(int i = 1; i < e; i += 1)
    {
      result *= b;
    }
    return result;
  }

  else if (e != 0 && b == 0)
  {
    return 0;
  }

  else if (e == 0 && b != 0)
  {
    return 1;
  }

  else if (b == 1)
  {
    return 1;
  }

  else if (e == 1)
  {
    return b;
  }

  else
  {
    cout << endl << "Error";
    return -1;
  }
}

int main ()
{
  cout << endl << pow(-2, -1);

  return 0;
}

输出 is :

b = 0

0

为什么 b 被设置为 0?

最佳答案

整数除法只能产生整数结果。您的程序导致这一行:

cout << "b = " << 1/b << endl;

运行,如果b是任何大于1的整数,结果将是0

关于c++ - C++ 中的幂函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14532432/

相关文章:

c++ - 如何在命名空间中导入 C++ 类的 dll

c++ - std::string — 小字符串优化和交换

c++ - 如何使用命令提示符,记事本和MinGW编译带有主文件,头文件和实现文件的C++程序?

c++ - 无法弄清楚 int[3][3] 和 int(* const)[3] 之间的区别

c++ - 从类型元组到通过调用模板函数返回的值数组

c++ - 无法让 Windows 覆盖图标在 TListView 中工作

c++ - 使用 C++ 和 opencv 进行图像缩放的 Spline Catmull-Rom

c++ - 钻石层次结构中的低落

c++ - 强制转换和 namespace 运算符之间没有空格?

C++如何在for循环中计算一次而不是多次