By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,955 Members | 1,756 Online
Bytes IT Community
+ Ask a Question
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
  1. // following in typedefs.h file
  2. typedef unsigned short int byte;
  3.  
  4. int rpm ;              // current rpm 
  5. float kwh = 3.3 ;      // Diesel Engine = 3.3KWh per litre
  6. byte maxPower = 44 ;   // maximum power of engine in kW at ...
  7. int maxRevs = 4000 ;   // ... maximum revs to give maxPower
  8. ...
  9. 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

✓ answered by MartijnHoekstra

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

Share this Question
Share on Google+
3 Replies


100+
P: 687
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.
Sep 6 '10 #2

P: 39
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)maxPower/kwh)
Sep 6 '10 #3

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

Post your reply

Sign in to post your reply or Sign up for a free account.