Why is my power operator (^) not working?(为什么我的幂运算符 (^) 不起作用?)
问题描述
#include <stdio.h>
void main(void)
{
int a;
int result;
int sum = 0;
printf("Enter a number: ");
scanf("%d", &a);
for( int i = 1; i <= 4; i++ )
{
result = a ^ i;
sum += result;
}
printf("%d
", sum);
}
为什么 ^
不能作为幂操作符?
Why is ^
not working as the power operator?
推荐答案
好吧,首先,C/C++ 中的 ^
运算符是按位异或.它与权力无关.
Well, first off, the ^
operator in C/C++ is the bit-wise XOR. It has nothing to do with powers.
现在,关于您使用 pow()
函数的问题,一些谷歌搜索表明将其中一个参数转换为double有帮助:
Now, regarding your problem with using the pow()
function, some googling shows that casting one of the arguments to double helps:
result = (int) pow((double) a,i);
请注意,我还将结果强制转换为 int
,因为所有 pow()
重载返回双精度值,而不是 int
.我没有可用的 MS 编译器,所以我无法检查上面的代码.
Note that I also cast the result to int
as all pow()
overloads return double, not int
. I don't have a MS compiler available so I couldn't check the code above, though.
从 C99 开始,还有 float
和 long double
分别称为 powf
和 powl
的函数,如果有帮助的话.
Since C99, there are also float
and long double
functions called powf
and powl
respectively, if that is of any help.
这篇关于为什么我的幂运算符 (^) 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我的幂运算符 (^) 不起作用?


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01