Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Why won't either of these work in C# ??

// Expected: 0.5, Output: 0

Console.WriteLine("Result #1: " + (50 / 100));

int iFifty = 50;
int iOneHundred = 100;
Console.WriteLine("Result #2: " + (iFifty / iOneHundred));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
217 views
Welcome To Ask or Share your Answers For Others

1 Answer

it is an integer division, you need doubles:

Console.WriteLine("Result #1: " + (50 / 100d));

Or:

Console.WriteLine("Result #1: " + (50 / 100.0));

If both operands are integer, an integer division is performing therefore you get an integer result.If you use 'd' literal you explicitly state that number should be considered as double and other operand is promoted to double automatically, then a double division is performing and you get the correct result.See C# Specification Section 2.4.4 Literals for more info about literals and also you migh want take a look at Floating-Point Types in C#


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...