All experienced programmers in C# (I think this comes from C) are used to cast on of the integers in a division to get the decimal / double / float result instead of the int (the real result truncated).

I'd like to know why is this implemented like this? Is there ANY good reason to truncate the result if both numbers are integer?

Yes, if the end result needs to be a whole number. It would depend on the requirements.

If these are indeed your requirements, then you would not want to store a decimal and then truncate it. You would be wasting memory and processing time to accomplish something that is already built-in functionality.

Calculating on integers is faster (usually) than on floating point values. Besides, all other integer/integer operations (`+`

, `-`

, `*`

) return an integer.

EDIT: As per the request of the OP, here's some addition:

The OP's problem is that they think of `/`

as division in the mathematical sense, and the `/`

operator in the language performs some other operation (which is not the math. division). By this logic they should question the validity of all other operations (`+`

, `-`

, `*`

) as well, since those have special overflow rules, which is not the same as would be expected from their math counterparts. If this is bothersome for someone, they should find another language where the operations perform as expected by the person.

As for the claim on perfomance difference in favor of integer values: When I wrote the answer I only had "folk" knowledge and "intuition" to back up the claim (hece my "usually" disclaimer). Indeed as Gabe pointed out, there are platforms where this does not hold. On the other hand I found this link (point 12) that shows mixed performances on an Intel platform (the language used is Java, though).

The takeaway should be that with performance many claims and intuition are unsubstantiated until measured and found true.

If you add an int to an int, you expect to get an int. If you subtract an int from an int, you expect to get an int. If you multiple an int by an int, you expect to get an int. So why would you not expect an int result if you divide an int by an int? And if you expect an int, then you will have to truncate.

If you don't want that, then you need to cast your ints to something else first.

Edit: I'd also note that if you really want to understand why this is, then you should start looking into how binary math works and how it is implemented in an electronic circuit. It's certainly not necessary to understand it in detail, but having a quick overview of it would really help you understand how the low-level details of the hardware filter through to the details of high-level languages.

The operator is designed to return the same type as it's input.

Edit (comment response): Why? I don't design languages, but I would assume most of the time you will be sticking with the data types you started with and in the remaining instance, what criteria would you use to automatically assume which type the user wants? Would you automatically expect a string when you need it? (sincerity intended)

Is there ANY good reason to truncate the result if both numbers are integer?

Of course; I can think of a dozen such scenarios easily. For example: you have a large image, and a thumbnail version of the image which is 10 times smaller in both dimensions. When the user clicks on a point in the large image, you wish to identify the corresponding pixel in the scaled-down image. Clearly to do so, you divide both the x and y coordinates by 10. Why would you want to get a result *in decimal*? The corresponding coordinates are going to be integer coordinates in the thumbnail bitmap.

Doubles are great for physics calculations and decimals are great for financial calculations, but almost all the work I do with computers that does any math at all does it entirely in integers. I don't want to be constantly having to convert doubles or decimals back to integers just because I did some division. If you are solving physics or financial problems then **why are you using integers in the first place?** Use *nothing* but doubles or decimals. Use integers to solve finite mathematics problems.

C# traces its heritage to C, so the answer to "why is it like this in C#?" is a combination of "why is it like this in C?" and "was there no good reason to change?"

The approach of C is to have a fairly close correspondence between the high-level language and low-level operations. Processors generally implement integer division as returning *a quotient and a remainder,* both of which are of the same type as the operands.

(So my question would be, "why doesn't integer division in C-like languages return *two integers*", not "why doesn't it return a floating point value?")

The solution was to provide separate operations for division and remainder, each of which returns an integer. In the context of C, it's not surprising that the result of each of these operations is an integer. This is frequently *more accurate* than floating-point arithmetic. Consider the example from your comment of `7 / 3`

. This value cannot be represented by a finite binary number *nor by a finite decimal number*. In other words, on today's computers, *we cannot accurately represent 7 / 3 unless we use integers!* The most accurate representation of this fraction is "quotient 2, remainder 1".

So, was there no good reason to change? I can't think of any, and I *can* think of a few good reasons *not* to change. None of the other answers has mentioned Visual Basic which (at least through version 6) has two operators for dividing integers: `/`

converts the integers to double, and returns a double, while `\`

performs normal integer arithmetic.

I learned about the `\`

operator after struggling to implement a binary search algorithm using floating-point division. It was really painful, and integer division came in like a breath of fresh air. Without it, there was lots of special handling to cover edge cases and off-by-one errors in the first draft of the procedure.

From that experience, I draw the conclusion that having different operators for dividing integers is confusing.

Another alternative would be to have only one integer operation, which always returns a double, and require programmers to truncate it. This means you have to perform two int->double conversions, a truncation and a double->int conversion every time you want integer division. And how many programmers would mistakenly round or floor the result instead of truncating it? It's a more complicated system, and at least as prone to programmer error, and slower.

Finally, in addition to binary search, there are many standard algorithms that employ integer arithmetic. One example is dividing collections of objects into sub-collections of similar size. Another is converting between indices in a 1-d array and coordinates in a 2-d matrix.

As far as I can see, no alternative to "int / int yields int" survives a cost-benefit analysis in terms of language usability, so there's no reason to change the behavior inherited from C.

In conclusion:

- Integer division is frequently useful in many standard algorithms.
- When the floating-point division of integers is needed, it may be invoked explicitly with a simple, short, and clear cast:
`(double)a / b`

rather than`a / b`

- Other alternatives introduce more complication both the programmer and more clock cycles for the processor.

Similar Questions

if pair end with a space char, why result value contains one dot(.)? what does this dot(.) mean? (cons 1 2 ) ;Value 2: (1 . 2) (car (cons 1 2 )) ;Value: 1 (cdr (cons 1 2 )) ;Value: 2 this one seems s

Division by zero in a C program results in abnormal termination with the error message Floating point exception (core dumped). This is unsurprising for floating point division, but why does it say thi

i have an if statement comparing two NSStrings, one is user input from a UITextField the other is a NSString created from random integers between 0-9 inclusive, however the comparison is failing every

How can I generate random integers numbers between 0<9 (included extremes) in python? i.e. 0 1 2 3 4 5 6 7 8 9

I have created a two functions which sorts integers from lowest value to highest then back to low. Does this type of sort exist? Anyways, I have the following two sorting functions which I have create

I just need to know the difference between two int variables a and b. I'm new to Objective-C.

I'm trying to generate random values between two integers. I've tried this, which start from 0, let randomNumber = arc4random_uniform(10) println(randomNumber) But I need to print values between 10 t

I recently ran into an issue that could easily be solved using modulus division, but the input was a float: Given a function which repeats (ex: sin), and a computer function that can only compute it

Microsoft technet suggests [Math]::Floor([int]$a / [int]$b) for integer division. I believe that [int][Math]::Floor($a / $b) is both more readable as well as more performant due to one less cast opera

Here is the pseudo code which computes division of two positive integers. HR register saves reminder, and LR saves dividend. (and eventually saves root) However I think this algorithm has some problem

I have 3 very large signed integers. long x = long.MaxValue; long y = long.MaxValue - 1; long z = long.MaxValue - 2; I want to calculate their truncated average. Expected average value is long.MaxVal

How do I compute the remainder of the division of two floats?

can any one please tell me what are the other ways to build the communication between two website's server without using nusoap

SELECT 9/2 gives 4 Why gives postgresql automatically rounded result? There are some option for prevent this? (That is, I need that after division, if result is float, returns exactly and not rounded

In an SQL statement, I am trying to divide two integers (integer 1 is abc in my code below, integer 2 is xyz in my code), and get a result as a decimal (def in my code below). The decimal result s

I was looking of border between two ListViews as shown in the attached screenshot(in red) and not the border(in white) among the ListView items. Any idea of how to set the border between the ListVie

How do I divide two integers to get a double?

I'm wondering why I'm not getting the same result form these two code blocks. var line = ; var counter = 0; while (counter < 10) { line = line + #; print(line); counter = counter + 1; } - var

This question already has an answer here: How can I divide two integers to get a double? 3 answers In my code I can't get the right division I don't know why I have for example ; int N =5; int

I have two tables A and B. Number of rows of A is x, number of rows of B is y, and I need to compute x/y. How to do all this in one sql request. Here is what I have tried so far : select round(final,

I have two integers that I need to pass through one integer and then get the values of two integers back. I am thinking of using Logic Operators (AND, OR, XOR, etc) . Can you help me on that?

I'm looking to assess similarity (including case) between two strings and give a value between 0 and 1. I tried the Levenshtein distance implementation but it only gives integers and does not compare

I have two sorted arrays of numbers. The first array is a set of n integers which are targets equally spaced between the bounds of the array. The second array has a large multiple of n integers and is

A question from a book I have found. Write a program that asks the user to input an integer and prints two integers, root and pwr, such that 0 < pwr < 6 and root**pwr is equal to the integer us

I use Python 2.7 within Python(x,y), a scientific-oriented Python distribution based on Qt and Spyder as IDE. When I use standard floor division of integers in the standard Python IDE the result is th

I have a table1 (records 3), and table2 (records 3). Where i have field name in both. Now i want to make a result from those two table which will show me both table records and take only one if the

I want to write some integers to a binary file and I want to force them to be written in two bytes even if a few of them don't fit (trim these). I get an error when I do this (below). Is there another

Hashing using division method means h(k) = k mod m . I read that m should not be power of 2. This is because if m = 2^p, h becomes just the p lowest-order bits of k. Usually we choose m to be a prim

Say I have the following checkbox: <input type=checkbox value=1-25 /> To get the two numbers that define the boundaries of range I'm looking for, I use the following jQuery: var value = $(t

I have a code which finds if there is more than one space between the words, in that case change them to one. And I need to add some additional function which should make two spaces between sentences.

I am working on Windows Phone Application. I need to concat two values which are integers and the result should be changed into float value. For example, a = 120 and b = 3. Then result c = 120.3 which

I was wondering if it's possible to set a double from two integers, say: int i = 1; int j = 2; double l = i.j; so hopefully have l set to 1.2. I'm currently trying this with a loop, but nothing is co

Modern CPU's can perform extended multiplication between two native-size words and store the low and high result in separate registers. Similarly, when performing division, they store the quotient and

I need to divide two numbers and round it up. Are there any better way to do this? int myValue = (int) ceil( (float)myIntNumber / myOtherInt ); I find an overkill to have to cast two different time.

Given an array of integers, i have to find out the maximum difference between any two elements such that larger number is appearing after the smaller number in the array.I used a simple approach and t

I'm looking to do the equivalent of SUMPRODUCT but with division. Is there a way to add the results from dividing two arrays? Example: Column A has the life of an asset in years (10, 20, 10). Column

If I have an odd number, how would I divide it in two and leave two integers, with the first being one more than the second. For instance 9 would produce 5 and 4?

I am in need of your help as I am struggling with a query in SQL. This query is not giving exact result that I want. I need to pull out all the dates between two dates. I tried two queries: SELECT a.M

Today i learned a bit about how floating point numbers are expressed binary. Well, i can see why the IEE-754 technical standard is smart for storing a huge range of numbers using relatively few bits.

I have created a database table in mySQL of which two column names are landPhone and mobilePhone to store phone numbers (in the format of: 123-456-8000 for land and 098-765-6601 for mobile). These

The problem is to find the numbers of squares between two numbers. The code below works small numbers but fails for huge numbers. How can I correct this? import java.io.*; import java.util.*; import

This question already has an answer here: Strange float division result 3 answers When i want to calculate 0.9623 - 0.9619 it returns: 4.0000000000006697E-4 Why is that? and how can i avo

I am looking for a way to be able to translate between single precision and double precision. One example would be to divide 2 integers and get a floating result. How is that possible?

Fiddle I have two Div , one is in table and other , outside of table . My problem is , as you can see , divOne overflow outside of parent Div . I want to show like --------------------- | ---- ----

Let's look at the following code snippet in Java. package division; import java.math.BigDecimal; final public class Main { public static void main(String[] args) { BigDecimal a = new BigDecimal(2); Bi

Why is it important to assume that integers in our computer model have a fixed size?

If I multiplie two 16-bit numbers, the result will be 32-bit long. But why is this so? What is the clear explanation for this? And for my right understanding: The calculation for this is: n-bit number

I need some division algorithm which can handle big integers (128-bit). I've already asked how to do it via bit shifting operators. However, my current implementation seems to ask for a better approac

When trying to pull using EGit with Eclipse I randomly get the error: packfile is truncated I don't know how and why this occurs. Even importing the project again doesn't help. What's the problem he

Why does NSLog(@%0.0f, 1.0/10.0); output 0? Isn't 1.0/10.0 division of two double values? Why is it rounding down to 0?