Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

Basic Maths C# Not Working

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

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

1 Reply

0 votes
by (71.8m points)

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#


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...