C# is rounding down divisions by itself
i = 200 / 3 is performing integer division. Try either: i = (double)200 / 3 or i = 200.0 / 3 or i = 200d / 3 Declaring one of the constants as a double will cause the double division operator to be used.
i = 200 / 3 is performing integer division. Try either: i = (double)200 / 3 or i = 200.0 / 3 or i = 200d / 3 Declaring one of the constants as a double will cause the double division operator to be used.
Use the int function to get the integer part of the result, truncated toward 0. This produces the nearest integer to the result, located between the result and 0. For example, int(3/2) is 1, int(-3/2) is -1. Source: The AWK Manual – Numeric Functions
You are missing the fact that 3 and 5 are integers, so you are getting integer division. To make the compiler perform floating point division, make one of them a real number: double f = 3.0 / 5;
The current answers all focus on decimal digits, when applying the “add all digits and see if that divides by 3”. That trick actually works in hex as well; e.g. 0x12 can be divided by 3 because 0x1 + 0x2 = 0x3. And “converting” to hex is a lot easier than converting to decimal. Pseudo-code: … Read more
Use div, which performs integer division: halfEvens :: [Int] -> [Int] halfEvens [] = [] halfEvens (x:xs) | odd x = halfEvens xs | otherwise = x `div` 2 : halfEvens xs The (/) function requires arguments whose type is in the class Fractional, and performs standard division. The div function requires arguments whose type … Read more
3 and 6 are both Int, and dividing one Int by another gives an Int: that’s why you get back 0. To get a non-integer value you need to get the result of the division to be a non-integer value. One way to do this is convert the Int to something else before dividing it, … Read more
You can call int() on the end result: >>> int(2.0) 2
The guy who said “leave it to the compiler” was right, but I don’t have the “reputation” to mod him up or comment. I asked gcc to compile int test(int a) { return a / 3; } for an ix86 and then disassembled the output. Just for academic interest, what it’s doing is roughly multiplying … Read more
Do floating point division then convert to an int. No extra modules needed. Python 3: >>> int(-1 / 2) 0 >>> int(-3 / 2) -1 >>> int(1 / 2) 0 >>> int(3 / 2) 1 Python 2: >>> int(float(-1) / 2) 0 >>> int(float(-3) / 2) -1 >>> int(float(1) / 2) 0 >>> int(float(3) / … Read more
Many languages have a “mod” or “%” operator that gives the remainder after division with truncation towards 0; for example C, C++, and Java, and probably C#, would say: (-11)/5 = -2 (-11)%5 = -1 5*((-11)/5) + (-11)%5 = 5*(-2) + (-1) = -11. Haskell’s quot and rem are intended to imitate this behaviour. I … Read more