Andrew
Andrew

Reputation: 16051

Confused with floats and ints

They're not the best of friends.

I have this:

int svNumberOfObjects = 9;

and this:

int svColumns = 4;

and then there's also this:

float numberOfRows = svNumberOfObjects/svColumns;

which comes out with this:

2.000000

How can i get it to show me the actual float value?

Upvotes: 3

Views: 131

Answers (3)

Bartosz Ciechanowski
Bartosz Ciechanowski

Reputation: 10333

You can also try

float numberOfRows = 1.0*svNumberOfObjects/svColumns;

Upvotes: 0

Stephen Canon
Stephen Canon

Reputation: 106167

float numberOfRows = (float)svNumberOfObjects/svColumns;

Your code at present uses integer division, which truncates the result to an integer. You want a floating-point division instead, which means that you need one of the operands to be a floating-point value; the explicit cast accomplishes this.

Upvotes: 10

ergosys
ergosys

Reputation: 49019

float numberOfRows = (float)svNumberOfObjects/svColumns;

Upvotes: 2

Related Questions