K Owen
K Owen

Reputation: 1250

Problems with float: it does not return the fraction

I am puzzled that a float does not return the fraction. The code:

float max_stops;
int maxBellows = 330;
int lensFocal = 135;
max_stops =  (maxBellows / lensFocal );

returns 2.0 instead of 2.44.

Can you pls help me get this right?

Upvotes: 1

Views: 259

Answers (5)

user467871
user467871

Reputation:

try these :

max_stops =  ((float)maxBellows / lensFocal );

or

max_stops =  (maxBellows / (float) lensFocal );

Upvotes: 2

Michael Borgwardt
Michael Borgwardt

Reputation: 346300

Your problem is not with float but with int - this maxBellows / lensFocal is a division of two int values, which means it will have an int result, no matter whether that result is then put into a float variable. To get a float result, you have to cast one of the operands to float before the calculation:

max_stops =  maxBellows / (float)lensFocal;

Upvotes: 2

computeALot
computeALot

Reputation: 19

The / operator for two ints returns an int. You need to divide by 135.0 or cast the variables to float or whatever

Upvotes: 2

nos
nos

Reputation: 229108

an int divided by an int yields an int.

Make one of the operands a float, e.g.

max_stops =  ((float)maxBellows / lensFocal );

Upvotes: 3

Rafe Kettler
Rafe Kettler

Reputation: 76955

Cast maxBellows and lensFocal to float. Since they're both ints, maxBellows / lensFocal returns an int, which then gets cast to float when it's assigned to max_stops. At least one of maxBellows and lensFocal should be cast to a float.

Upvotes: 7

Related Questions