Learning C (again) and running into problems
2004-10-20 09:44:46 ET

Okay, this compiles but gives me an output of only zeroes. Why?


Source code:

#include <stdio.h>

int main()
{
int start, end, step;
int f, c;

start = 0;
end = 300;
step = 20;
f = 0;
c = (f-32)*(5/9);

for(f=start; f <= end; f + step) printf(" %d\t%d\n", f, c);
return 0;
}


Why does this only return zeroes?!


2004-10-20 10:13:13 ET

for(f=start; f <= end; f + step)

The third section of the if statement should assign a new value to a variable (presumably f) during each iteration of the loop. Your statement within this section is valid which is why it compiles and runs, but since you don't ever change the value of f, the loop will run indefinitely. Perhaps you meant

for(f=start; f <= end; f += step) ?

2004-10-20 10:45:14 ET

Your formatting is off. %d is for decimals/floats. Use %i. or...

Actually, since you're expecting decimals/floats or doubles. Initialize f and c as floats.

2004-10-20 15:26:55 ET

AAaaargh! You're right!

/smacks forehead so hard that the hand leaves a palm print right in the centre of the forehead.

2004-11-09 17:56:14 ET

I should give you the explanation of what was wrong.

I thought it was what Tetesuro mentioned but then found out that my book didn't mention %i in the beginning. It said to use %d even for integers.

The problem was (5/7). In C, whenever you get a decimal as a result of integer math any numbers to the right of the decimal point are dropped. So that makes "(5/7)" = "0" in integer math. Thus all my results came back as "0"

  Return to LeoZ's page