Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do the division (/) operators behave differently in VB.NET and C#?

Tags:

If you create new projects in C# and VB.NET, then go directly in the Immediate Window and type this:

? 567 / 1000 

C# will return 0, while VB.NET will return 0.567.

To get the same result in C#, you need to type

? 567 / 1000.0 

Why is there this difference? Why does C# require the explicit decimal point after 1000?

like image 560
Fredou Avatar asked Dec 23 '09 14:12

Fredou


People also ask

Why does VB.NET support two kinds of division operators?

Because in VB.NET, the / operator is defined to return a floating-point result. It widens its inputs to double and performs the division. In C#, the / operator performs integer division when both inputs are integers.

How does division work in C#?

When you divide two integers, C# divides like a child in the third grade: it throws away any fractional remainder. Thus, dividing 17 by 4 returns a value of 4 (C# discards the remainder of 1).

Which operator is used to divide one operand by another and returns a result in decimal form?

/ Operator (Visual Basic)

How do you divide in Visual Basic?

Integer division is carried out using the \ Operator (Visual Basic). Integer division returns the quotient, that is, the integer that represents the number of times the divisor can divide into the dividend without consideration of any remainder.


1 Answers

The / operator in C# for integer operands does the "integer division" operation (equivalent to \ operator in VB.NET). For VB.NET, it's the "normal" division (will give fractional result). In C#, in order to do that, you'll have to cast at least one operand to a floating point type (e.g. double) explicitly.

like image 73
mmx Avatar answered Sep 20 '22 05:09

mmx