integer division question

J

J.Marsch

Suppose that I have an integer division problem, but I want the answer was a
float. What's the cleanest syntax for that?

Example:
In this code, the variable z ends up == 0. And that is correct, because
this is integer division and the values are trunc'd. No problem. But
what's the most elegant code given that x and y have to be ints, and I want
z to be a float or double?

Code:
public static void Main()
{
int x = 50;
int y = 100;
float z = x / y; // z == 0, just like it's supposed to
Console.WriteLine(z.ToString());
}


Now, I know I could do this (below), but is there a better way?

public static void Main()
{
int x = 50;
int y = 100;
float x1 = x;
float y1 = y;
float z = x1 / y1; // z == 0.5, just like it's supposed to
Console.WriteLine(z.ToString());
}
 
J

J.Marsch

Yep, that works. thought of that immediately after hit send. D'oh!
Thanks, Fred. Just out of curiosity, I might have to bounce down to the
IL -- I wonder if the same pair of temporary variables has to be created
under the covers.
 
D

David Browne

Fred Mellender said:
How about

float z = (float)x / (float)y;
Nope. That'll return fractions.

How about

int x = 1;
int y = 3;
float z = (float)(x/y);

David
 
J

Jon Skeet [C# MVP]

Nope. That'll return fractions.

That's the idea.
How about

int x = 1;
int y = 3;
float z = (float)(x/y);

That will return 0, which isn't the desired answer.

From the original post (using 1 and 2):

<quote>
// z == 0.5, just like it's supposed to
</quote>

Casting *either* the numerator *or* the divisor is enough to make the
whole operation a floating point one though.
 
D

David Browne

Jon Skeet said:
That's the idea.


That will return 0, which isn't the desired answer.

From the original post (using 1 and 2):

<quote>
// z == 0.5, just like it's supposed to
</quote>

Perhaps next time I'll read the post.

David
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top