Programming Noob Programming Noob - 1 year ago 78
C Question

Program doesn't calculate as expected

So I'm pretty new to programming and I just can't seem to see anything wrong with my code:

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);

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



Desired output:

0.5*9.8*(1^2) = 4.90

Actual output:

0.5*9.8*(3) = 14.70

Now if t=1, fallD should be 0.5*9.8*(1^2) = 4.90 but the output is 14.70. Any idea why?

Answer Source

In C, there is no ^ operator for expotentation. Use Grav(t*t). There is no syntax error though, because ^ is bitwise XOR operator. It takes two numbers and perform XOR on their corresponding bits.

for example, when t=6 t^2 will be:

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

You can also use pow function from Math library. Some introduction can be found on tutorialspoint.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download