C ^(破折号)指数运算符如何工作?

时间:2016-11-05 08:24:38

标签: c calc

我对编程很陌生,我无法找到我的输出与所需输出不同的原因。这是我的代码:

#include<stdio.h>

float fallingDistance (int t);
int main () {
    int t;
    float result=0.0;
    printf("t <seconds>\td <meters>\n");
    for(t=1;t<=10;t++) {
        result = fallingDistance (t);
        printf("\t%d\t%.2f\n",t,result);
    }
}

float fallingDistance (int t) {
    const float Grav = 9.8;
    float fallD = 0.5*Grav*(t^2);
    return fallD;
}

我的输入是:

t=1

期望的输出:

0.5*9.8*(1^2) = 4.90

实际输出:

0.5*9.8*(3) = 14.70

现在如果t = 1,fallD应为0.5 * 9.8 *(1 ^ 2)= 4.90,但输出为14.70。知道为什么吗?

1 个答案:

答案 0 :(得分:10)

在C中,没有^运算符用于expotentation。使用Grav(t*t)。但是没有语法错误,因为^是按位XOR运算符。它需要两个数字并对相应的位执行XOR。

例如,当t=6 t^2为:

6:   110
2:   010
6^2: 100 which in dec is 4.

您还可以使用pow库中的Math功能。可以在tutorialspoint上找到一些介绍。

按位异或按以下方式工作:它采用两个数字的所有位并比较相同位置的位(从结束开始计数)。差异标记为1,没有差异(相等)标记为0。

定义:

a   b  a^b
-----------
0   0   0
0   1   1
1   0   1
1   1   0

示例:

10 ^ 4 = 1010_2 ^ 100_2 = 1110_2 = 14  //_2 stands for binary

,因为:

 1010
^ 100
-----
=1110