Division in VB.NET

前端 未结 4 1914
隐瞒了意图╮
隐瞒了意图╮ 2021-01-01 19:13

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 b

相关标签:
4条回答
  • 2021-01-01 19:23

    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.

    0 讨论(0)
  • 2021-01-01 19:24
    10 / 3 = 3.333
    10 \ 3 = 3 (the remainder is ignored)
    
    0 讨论(0)
  • 2021-01-01 19:33
    10 / 3 = 3.33333333333333, assigned to integer = 3
    10 \ 3 = 3, assigned to integer = 3
    20 / 3 = 6.66666666666667, assigned to integer = 7
    20 \ 3 = 6, assigned to integer = 6
    

    Code for the above:

    Dim a, b, c, d As Integer
    a = 10 / 3
    b = 10 \ 3
    c = 20 / 3
    d = 20 \ 3
    
    Debug.WriteLine("10 / 3 = " & 10 / 3 & ", assigned to integer = " & a)
    Debug.WriteLine("10 \ 3 = " & 10 \ 3 & ", assigned to integer = " & b)
    Debug.WriteLine("20 / 3 = " & 20 / 3 & ", assigned to integer = " & c)
    Debug.WriteLine("20 \ 3 = " & 20 \ 3 & ", assigned to integer = " & d)
    
    0 讨论(0)
  • 2021-01-01 19:43
    / Division
    \ Integer Division
    
    0 讨论(0)
提交回复
热议问题