开发者

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

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开发者_JAVA技巧 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?


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.


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.

See MSDN for VB.NET.

Divides two numbers and returns a floating-point result.

Before division is performed, any integral numeric expressions are widened to Double.

See MSDN for C#.

The division operator (/) divides its first operand by its second. All numeric types have predefined division operators.

When you divide two integers, the result is always an integer.

To get the same semantics in VB.NET as the / operator on integers in C#, use the \ operator.

Divides two numbers and returns an integer result.


By default C# is treating 576 / 1000 as integer division so you get an integer as the result.

In VB.NET it's treating it as floating point division.

By adding ".0" on a number in C# you are explicitly telling it this number is a floating point number and hence the division becomes floating point as well.


The languages are different. In C# the compiler interprets those numbers as integers and uses integer division. In VB.NET the compiler uses floating point division.


C# Language Reference

VB.Net Language Reference

VB.Net has both a / and a \ operator. / happens to be the floating point division operator.


C#'s / equalant in VB.Net is \

C#.Net:

/ Operator Divides two numbers and returns an integer result.

VB.Net:

/ Operator Divides two numbers and returns a floating-point result.

\ Operator Divides two numbers and returns an integer result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜