为什么我的幂运算符 (^) 不起作用? [英] Why is my power operator (^) not working?

查看:47
本文介绍了为什么我的幂运算符 (^) 不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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 开始,还有 floatlong double 分别称为 powfpowl 的函数,如果有帮助的话.

Since C99, there are also float and long double functions called powf and powl respectively, if that is of any help.

这篇关于为什么我的幂运算符 (^) 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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