5

Possible Duplicate:
C programming division

I'm trying to calculate the period of accelerometer updates using a user entered frequency.

this is my code:

double interval = 1/Freq;

interval = period

Freq is an int set by the user.

The problem I'm having is lets say I set Freq to 2Hz so the interval should be 0.5 but instead interval is 0.0000000 why is this? Can I do anything to change it without changing Freq to a double?

Community
  • 1
  • 1
Mike Khan
  • 595
  • 1
  • 7
  • 18
  • 1
    why not declare a temporary double which you use for the calculation, leaving `Freq` an int, doing `1.0/tmpFreq` ? –  Feb 20 '12 at 14:57

2 Answers2

7

You are using integer division: (both 1 and Freq are integers). So the result will be an integer, and more exactly 0 in this case.

You can do something like this:

double interval = 1.0 / Freq;

Or

double interval = 1 / (double)Freq;
sch
  • 27,436
  • 3
  • 68
  • 83
0

do it this way,

double interval = 1.0/Freq;
karim
  • 15,408
  • 7
  • 58
  • 96