为什么我的电源运算符 (^) 不起作用?

新手上路,请多包涵
#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\n", sum);
}

为什么 ^ 不能作为电力运营商工作?

原文由 Abid Ali 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 631
2 个回答

好吧,首先,C/C++ 中的 ^ 运算符是按位异或。这与权力无关。

现在,关于您使用 pow() 函数的问题, 一些谷歌搜索 显示将参数之一转换为 double 有助于:

 result = (int) pow((double) a,i);

请注意,我还将结果转换为 int 因为所有 pow() 重载返回双倍,而不是 int 。我没有可用的 MS 编译器,所以我无法检查上面的代码。

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

原文由 Sergei Tachenov 发布,翻译遵循 CC BY-SA 3.0 许可协议

它不起作用,因为 c 和 c++ 没有任何运算符来执行幂运算。

您可以做的是,您可以使用 math.h 库并使用 pow 函数。有一个函数代替运算符。

 `   #include<stdio.h>
    #include<math.h>
    int main(){
        int base = 3;
        int power = 5;
        pow(double(base), double(power));
        return 0;
     }`

原文由 Brijal Kansara 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题