C语言 c - 如何在c中使用x的幂

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7458072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:39:24  来源:igfitidea点击:

How to use raise to the power of x in c

c

提问by Spencer

My question is how do I compute 2^(x) in c. I know there is something like shifting that does the same thing. I tried to do total = x << 1, but that didn't work. I know that if i shift one bit it is the same as multiplying it by two. Or something like that.

我的问题是如何在 c 中计算 2^(x)。我知道有类似的东西可以做同样的事情。我试图做 total = x << 1,但这没有用。我知道如果我移动一位,它与乘以二是一样的。或类似的东西。

int x;

for(x=0; x<4; x++){

total += x <<1; // 

}

When this is done executing I expect the total to be 15 ( 20+ 21+ 22+ 23)

执行完毕后,我预计总数为 15 ( 2 0+ 2 1+ 2 2+ 2 3)

Any ideas on what I am doing wrong? my total starts off as being 0 and then messes up.

关于我做错了什么的任何想法?我的总数开始为 0,然后一团糟。

Thanks!

谢谢!

回答by K-ballo

It's the other way around. 1 << xwill give you '2 ^ x'.

正好相反。1 << x会给你'2 ^ x'。

回答by Thomas Eding

This should do what you want. Call pow(2, x)to get 2x.

这应该做你想做的。调用pow(2, x)以获取 2 x

int abs (int x) {
  if (x < 0) return -x;
  return x;
}

int signum (int x) {
  if (x < 0) return -1;
  if (x > 0) return 1;
  return 0;
}

int add (int x, int y) {
  for (int i = 0; i < abs(y); ++i) {
    if (y > 0) ++x;
    else --x;
  }
  return x;
}

int mult (int x, int y) {
  int sign = signum(x) * signum(y);
  x = abs(x);
  y = abs(y);
  int res = 0;
  for (int i = 0; i < y; ++i) {
    res = add(res, x);
  }
  return sign * res;
}

int pow (int x, int y) {
  if (y < 0) return 0;
  int res = 1;
  for (int i = 0; i < y; ++i) {
    res = mult(res, x);
  }
  return res;
}

回答by Brian Coleman

Left shift is limited to the word size of your CPU, either 32 or 64 bits, which limits the maximum exponent which you can safely use, before the result is undefined (2^31 or 2^63).

左移仅限于 CPU 的字大小,32 位或 64 位,这限制了您可以安全使用的最大指数,然后结果未定义(2^31 或 2^63)。

The following works for larger exponents but uses floating point arithmetic. If you need exact results you should consider using a infinite precision maths library such as GMP

以下适用于较大的指数,但使用浮点运算。如果您需要精确的结果,您应该考虑使用无限精度数学库,例如GMP

#include <math.h>

int main() {
  double base = 2;
  double exponent = 4;

  double result = pow(base, exponent);

  return 0;
}