1

我正在玩幂函数的实现:

#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;
}

输出

b = 0

0

为什么 b 设置为 0?

4

2 回答 2

3

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

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

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

于 2013-01-26T00:28:14.220 回答
2

我不会说b设置为 0。在你的函数中你有这个语句:

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

因为b是整数,1/b所以是整数除法,值最终是0

于 2013-01-26T00:27:51.750 回答