如何提升力量 [英] How to raise to the power of

查看:67
本文介绍了如何提升力量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C很陌生

我正在尝试将某些东西发挥某些作用

I am trying to put something to the power of something

例如5 ^ 3 = 125;

eg. 5^3=125;

但是当我编码时

#include <math.h>
...

printf("%d", 5^3);

我得到6.我在做根本上是错的事情吗?

I get 6. Am i doing something fundamentally wrong??

推荐答案

^是C语言中按位XOR运算符.

^ is the bitwise XOR operator in C.

5是二进制形式的1013011.所以101 XOR 011 = 110,它是十进制的6.

5 is 101 in binary representation and 3 is 011. So 101 XOR 011 = 110, which is 6 in decimal.

您想要的是pow(5,3)(在包含math.h之后即可使用).但是请注意,它作用于双精度数而不是整数,因此您的返回值将是一个浮点数,并且通常不精确.如果需要精确的整数幂运算,则要么必须使用其他库,要么实现自己的幂函数.这并不难,对于算法,请参见通过平方求幂.标准C不包含用于整数幂运算的函数.无论如何,对于整数幂运算,重要的是要注意溢出,对于较小的输入值可能已经发生

What you want is pow(5,3) (which is available after including math.h as you did). Note however that it acts on doubles not integer, so your return value will be a floating point and in general not exact. If you need exact integer exponentiation, then you either have to use an additional library or implement your own power-function. This is not that hard, for an algorithm see exponentiation by squaring. Standard C does not include a function for integer exponentiation. Anyway with integer exponentiation it is important to take care of overflows, which may happen already for small input values.

也要打印返回的双精度型,您要么将双精度型转换为整数printf("%d", (int)pow(5,3)),要么将其打印为浮点型printf("%f", pow(5,3))

Also to print the returned double you either have to cast the double to an int printf("%d", (int)pow(5,3)) or print it as floating point printf("%f", pow(5,3))

这篇关于如何提升力量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆