【问题标题】:Exponent not working properly in C指数在 C 中无法正常工作
【发布时间】:2014-04-16 17:51:00
【问题描述】:

当我运行以下代码时

/*Program to find the greatest common divisor of two nonnegative integer
 values*/


#include <stdio.h>

int main(void){
    printf("    n  |  n^2\n");
    printf("-----------------\n");
    for(int n = 1; n<11; n++){
        int nSquared = n^2;
        printf("%i          %i\n",n,nSquared);
    }
}

返回到终端的表格如下所示

    n  |  n^2
-----------------
1          3
2          0
3          1
4          6
5          7
6          4
7          5
8          10
9          11
10          8

为什么“n^2”端会生成错误的数字?有没有办法在 C 中编写上标和下标,所以我不必显示“n^2”而可以将列的那一侧显示为“n²”?

【问题讨论】:

  • 您关于写上标和下标的问题与您关于求幂的问题无关。我建议您将其作为一个单独的问题提交。 (这不是一件简单的事情,它可能取决于您的语言环境设置。)
  • 哈哈.. 我第一次看到有人期望 ^ 是 C 中的指数。
  • @bolov 看来您是这个网站的新手。这可能是我白天看到的第三个。似乎很多人都有这个任务到期。

标签: c exponent


【解决方案1】:

使用math.h 中的pow 函数。

^ 是按位异或运算符,与幂函数无关。

【讨论】:

    【解决方案2】:

    ^ 是异或运算。您要么想使用 math.h 函数“pow”,要么自己编写。

    【讨论】:

    • pow 对数字进行平方是多余的,并且会出现浮点舍入错误。写int nSquared = n*n;
    • @OMGtechy 我不认为这是正确的。 n &lt;&lt; 1n * n 不同。
    • @Whymarrh 我在搞混别的东西,谢谢指出。
    【解决方案3】:

    ^ 是按位异或运算符。您应该使用在math.h 标头中声明的pow 函数。

    #include <stdio.h>
    #include <math.h>
    
    int main(void) {
        printf("    n  |  n^2\n");
        printf("-----------------\n");
        for(int n = 1; n < 11; n++){
            int nSquared = pow(n, 2); // calculate n raised to 2
            printf("%i          %i\n", n, nSquared);
        }
        return 0;
    }
    

    通过标志 -lm 包含数学库以进行 gcc 编译。

    【讨论】:

      【解决方案4】:

      正如其他人指出的那样,问题在于^ 是按位异或运算符。 C 没有指数运算符。

      建议您使用pow() 函数来计算int 值的平方。

      这可能有效(如果您小心的话),但这不是最好的方法。 pow 函数接受两个 double 参数并返回 double 结果。 (有powfpowl 函数分别在floatlong double 上运行。)这意味着pow 必须能够处理任意浮点指数;例如,pow(2.0, 1.0/3.0) 将为您提供 2 的立方根的近似值。

      与许多浮点运算一样,pow 可能会出现舍入错误。 pow(3.0, 2.0) 可能会产生比 9.0 略小的结果;将其转换为int 会给你8 而不是9。即使你设法避免了这个问题,从整数转换为浮点,执行昂贵的操作,然后再转换回整数也是巨大的矫枉过正。 (实现可能使用整数指数优化对pow 的调用,但我不会指望这一点。)

      有人说(有点夸张)过早的优化是万恶之源,花在额外计算上的时间不太可能引起注意。但在这种情况下,有一种方法可以做你想做的事,它既简单又高效。而不是

      int nSquared = n^2;

      这是不正确的,或者

      int nSquared = pow(n, 2);
      

      效率低下,可能不可靠,直接写吧:

      int nSquared = n * n;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-23
        • 1970-01-01
        相关资源
        最近更新 更多