Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division in VB.NET

What's the difference between / and \ for division in VB.NET?

My code gives very different answers depending on which I use. I've seen both before, but I never knew the difference.

like image 987
Cyclone Avatar asked Dec 03 '10 01:12

Cyclone


People also ask

What is div integer division?

The % (integer divide) operator divides two numbers and returns the integer part of the result. The result returned is defined to be that which would result from repeatedly subtracting the divisor from the dividend while the dividend is larger than the divisor.

What is division in coding?

Division (/) The division operator ( / ) produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.

What is the symbol for integer division?

Names and symbols used for integer division include div, /, \, and %. Definitions vary regarding integer division when the dividend or the divisor is negative: rounding may be toward zero (so called T-division) or toward −∞ (F-division); rarer styles can occur – see modulo operation for the details.

What is the difference between division and integer division?

Integer division returns the floor of the division. That is, the values after the decimal point are discarded.


2 Answers

There are two ways to divide numbers. The fast way and the slow way. A lot of compilers try to trick you into doing it the fast way. C# is one of them, try this:

using System;

class Program {
    static void Main(string[] args) {
        Console.WriteLine(1 / 2);
        Console.ReadLine();
    }
}

Output: 0

Are you happy with that outcome? It is technically correct, documented behavior when the left side and the right side of the expression are integers. That does a fast integer division. The IDIV instruction on the processor, instead of the (infamous) FDIV instruction. Also entirely consistent with the way all curly brace languages work. But definitely a major source of "wtf happened" questions at SO. To get the happy outcome you would have to do something like this:

    Console.WriteLine(1.0 / 2);

Output: 0.5

The left side is now a double, forcing a floating point division. With the kind of result your calculator shows. Other ways to invoke FDIV is by making the right-side a floating point number or by explicitly casting one of the operands to (double).

VB.NET doesn't work that way, the / operator is always a floating point division, irrespective of the types. Sometimes you really do want an integer division. That's what \ does.

like image 105
Hans Passant Avatar answered Sep 23 '22 19:09

Hans Passant


10 / 3 = 3.333
10 \ 3 = 3 (the remainder is ignored)
like image 41
neo2862 Avatar answered Sep 22 '22 19:09

neo2862