424,955 Members | 1,756 Online
Need help? Post your question and get tips & solutions from a community of 424,955 IT Pros & Developers. It's quick & easy.

Mixed calculations with integers and floats in C?

 P: 45 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: Expand|Select|Wrap|Line Numbers // 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! :) Sep 6 '10 #1

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)maxPower/kwh)