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

问题描述

#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() 函数的问题,一些谷歌搜索表明将参数之一转换为双重帮助:

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.

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

09-05 18:24