基础数学C#不工作

-2 c# math

为什么这些都不能在C#中工作?

// Expected: 0.5, Output: 0

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

int iFifty = 50;
int iOneHundred = 100;
Console.WriteLine("Result #2: " + (iFifty / iOneHundred));
Run Code Online (Sandbox Code Playgroud)

Sel*_*enç 5

它是一个整数除法,你需要双打:

Console.WriteLine("Result #1: " + (50 / 100d));
Run Code Online (Sandbox Code Playgroud)

要么:

Console.WriteLine("Result #1: " + (50 / 100.0));
Run Code Online (Sandbox Code Playgroud)

如果两个操作数integer,一个整数除法正在执行,因此你会得到一个integerresult.If你用'd'文字可以明确这个数字应被视为double和其他操作数提升为double自动,然后一个双师正在执行,你会得到正确的结果.C# Specification Section 2.4.4 Literals有关文字的更多信息,请参阅,您也想看看Floating-Point Types in C#