473,738 Members | 9,555 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

integer division question

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.WriteLi ne(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.WriteLi ne(z.ToString() );
}
Nov 16 '05 #1
6 35293
How about

float z = (float)x / (float)y;
"J.Marsch" <je****@ctcdeve loper.com> wrote in message
news:%2******** **********@TK2M SFTNGP09.phx.gb l...
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.WriteLi ne(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.WriteLi ne(z.ToString() );
}

Nov 16 '05 #2
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.

"Fred Mellender" <no************ ****@frontierne t.net> wrote in message
news:o2******** *********@news0 2.roc.ny...
How about

float z = (float)x / (float)y;
"J.Marsch" <je****@ctcdeve loper.com> wrote in message
news:%2******** **********@TK2M SFTNGP09.phx.gb l...
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.WriteLi ne(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.WriteLi ne(z.ToString() );
}


Nov 16 '05 #3

"Fred Mellender" <no************ ****@frontierne t.net> wrote in message
news:o2******** *********@news0 2.roc.ny...
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
Nov 16 '05 #4
"Fred Mellender" <no************ ****@frontierne t.net> wrote:
How about
float z = (float)x / (float)y;


I think that just casting the divisor is enough.

float z = x / (float) y;

P.
Nov 16 '05 #5
<"David Browne" <davidbaxterbro wne no potted me**@hotmail.co m>> wrote:

"Fred Mellender" <no************ ****@frontierne t.net> wrote in message
news:o2******** *********@news0 2.roc.ny...
How about

float z = (float)x / (float)y;
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.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
<"David Browne" <davidbaxterbro wne no potted me**@hotmail.co m>> wrote:

"Fred Mellender" <no************ ****@frontierne t.net> wrote in message
news:o2******** *********@news0 2.roc.ny...
How about

float z = (float)x / (float)y;

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>


Perhaps next time I'll read the post.

David
Nov 16 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

16
1788
by: Frank | last post by:
Hi, can anybody help with the following problem? In C++ i = 5 / 10 and i = -5 / 10 both have the same result 0. In python
2
1918
by: Sebastian Haase | last post by:
Hi, I'm interested in having more people in our lab using numarray/NumPy instead of MatLab. For that I have put together a couple useful modules and written many myself. But then I got reminded of a new / upcoming feature of Python: "2/3 == 1.5" AKA PEP 238. I'm very interested in putting lots of "from __future__ import division" lines into my code especially since numarray (the new NumPy) now supports it.
19
5170
by: Imbaud Pierre | last post by:
integer division and modulo gives different results in c and python, when negative numbers are involved. take gdb as a widely available c interpreter print -2 /3 0 for c, -1 for python. more amazing, modulos of negative number give negative values! (in c). from an algebraic point of view, python seems right, but I thought python conformity to the underlying c compiler was a strong commitment, obviously not here, and I found no...
24
19384
by: Teis Draiby | last post by:
In .NET, can I be sure that the result of a division between two integers always is truncated rather that rounded to nearest? Example: 99 / 50 = 1 regards, Teis
3
6122
by: Janice | last post by:
I got this question from my textbook and I cannot understand the theory. When a signed positive integer X divided by pow(2,k), the result is shifting k bits to right and putting w-k bits of 0 from the most significant bits. However, when the X is a negative number divided by pow(2,k), the shifting and sign bit extension method doesnt give the correct answer? What kind of bias should we make on the X before the division? Thanx
10
3191
by: Mike S | last post by:
Does anyone know the logic behind why in VB.NET the result of a floating-point division ('/') is -rounded- on being converted to an integer type, such as with statements like Dim x As Integer = 2/3 'after assignment, x is 1, whereas a sane person would say it should be 0 Does Microsoft have a reason for this design decision? I understand that this type of rounding can reduce the overall error in long computation chains by reducing the...
8
6560
by: Candace | last post by:
I am using the following code to pick off each digit of a number, from right to left. The number I am working with is 84357. So for the first iteration it should return the number 7 and for the second iteration it should return the number 5, and so on. But for some reason on the first iteration returns the expected results. Each subsequent iteration returns the number plus 1. In order words, when I run the program I am getting: 7, 6, 4, and...
5
1605
by: bdsatish | last post by:
How does (a/b) work when both 'a' and 'b' are pure integers ? 4 -5 Why is it -5 ? I expect it to be -4 ? Because, in C/C++, 9/2 is 4 and so negative of it, (-9/2) is -4. What should I do to get C-like behavior ?
14
5166
by: Default User | last post by:
Hi, If I have three 64 bit integers and I want to do this operation on them: x*y/z Lets say that what we are multiplying by (y) is offset by what we are dividing by (z) so that the final answer will fit in a 64-bit integer. Let me simplify it by using unsigned chars (8 bits):
0
9476
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9335
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9263
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9208
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8210
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6751
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2745
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.