Mixed calculations with integers and floats in C?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nigelmercier
    New Member
    • Dec 2009
    • 45

    Mixed calculations with integers and floats in C?

    I'm trying to do a calculation that should be simple, but I keep getting a spurious answer of zero. It involves the rate of fuel use of an engine, the formula I'm using is:
    Rate of fuel use = (RPM / Max RPM)^3 * (Max Engine Power / 3.3)
    where 3.3 is the number of kWh produced by 1 litre of fuel). My code is as follows:

    Code:
    // following in typedefs.h file
    typedef unsigned short int byte;
    
    int rpm ;              // current rpm 
    float kwh = 3.3 ;      // Diesel Engine = 3.3KWh per litre
    byte maxPower = 44 ;   // maximum power of engine in kW at ...
    int maxRevs = 4000 ;   // ... maximum revs to give maxPower
    ...
    litPerHour = pow((rpm/maxRevs), 3)*(maxPower/kwh) ;//
    Library function:
    double pow(double x, double y); //returns the value of x raised to the power y

    I guess that I'm running out of precision somewhere, but I can't spot it.
    Any suggestions?
    Please note: I'm 50+, this is *not* homework! :)
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    rpm/maxRevs is calculated in integer, result is 0 if rpm is less than 4000.
    (double)rpm/maxRevs will cast rpm to double first and will fix it.

    Comment

    • MartijnHoekstra
      New Member
      • Sep 2010
      • 39

      #3
      i am concerned about your 'rpm/maxRevs' devision.
      You are now working with rounded numbers, which is good if you only want fraction-less numbers.
      for every number of rpm smaller than 4000, you will have pow(0,3).
      If you want to perform this calculation with fractions, try casting to doubles.

      litPerHour = pow( (double)rpm/(double)maxRevs , 3 ) * ...

      same counts for the latter part: ((double)maxPow er/kwh)

      Comment

      • nigelmercier
        New Member
        • Dec 2009
        • 45

        #4
        D'OH! Thanks for the replies, all working now. You can tell it's been a while since I did any math!

        Comment

        Working...