分部归零

Zo *_*Has 36 c#

我有这个简单的计算,返回零无法弄明白

decimal share = (18 / 58) * 100;
Run Code Online (Sandbox Code Playgroud)

Dan*_*Lee 51

你在这里使用整数.尝试对计算中的所有数字使用小数.

decimal share = (18m / 58m) * 100m;
Run Code Online (Sandbox Code Playgroud)

  • 为什么文字“18”被编译成整数本身并不明确。澄清一下,根据语言规范(词法结构 > 标记 > 文字),使用“十进制数字”0 到 9 编写的任何文字都是 [整数文字](https://msdn.microsoft.com/en-us/library/aa664674 (v=vs.71).aspx) 编译成“可以表示其值的这些类型中的第一个:`int`、`uint`、`long`、`ulong`。”,一旦添加了“ m" 后缀,文字现在被视为 [Real Literal](https://msdn.microsoft.com/en-us/library/aa691085(v=vs.71).aspx),它编译为类型 `decimal`。 (2认同)

Pet*_*nov 23

18 / 58 是整数除法,结果为0.

如果要进行十进制除法,则需要使用十进制文字:

decimal share = (18m / 58m) * 100m;
Run Code Online (Sandbox Code Playgroud)

  • 那对我来说是新的,我只是关注我的计算器. (4认同)

Kra*_*ime 10

由于有些人从计算结果为0的任何线程链接到这个,我将其添加为解决方案,因为并非所有其他答案都适用于案例场景.

需要对各种类型进行计算以便获得该类型的概念适用,但是上面仅显示"十进制"并使用它的简短形式,例如作为18m要计算的变量之一.

// declare and define initial variables.
int x = 0;
int y = 100;

// set the value of 'x'    
x = 44;

// Results in 0 as the whole number 44 over the whole number 100 is a 
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );

// Results in 0 as the whole number 44 over the whole number 100 is a 
// fraction less than 1, and thus is 0. The conversion to double happens 
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );

// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Run Code Online (Sandbox Code Playgroud)