分部归零

时间:2012-02-15 06:33:40

标签: c#

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

decimal share=(18 / 58)*100;

7 个答案:

答案 0 :(得分:47)

你正在使用整数。尝试对计算中的所有数字使用小数。

decimal share = (18m / 58m) * 100m;

答案 1 :(得分:23)

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

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

decimal share = (18m / 58m) * 100m;

答案 2 :(得分:8)

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

需要对各种类型进行计算以获得该类型作为结果的概念适用,但上面仅显示“十进制”并使用它的简短形式如// 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() ); 作为变量之一计算

<ul id="cordinates">
    <li id="lat" data-value="52.0193">52.0193</li>
    <li id="lon" data-value="23.2413">23.2413</li>
</ul>

答案 3 :(得分:3)

因为数字是整数而你执行整数除法。

18 / 58在整数除法中为0

答案 4 :(得分:2)

每当我遇到这种情况时,我只是将分子向上翻。

double x = 12.0 / 23409;
decimal y = 12m / 24309;

Console.WriteLine($"x = {x} y = {y}");

答案 5 :(得分:1)

十进制份额=(18 * 100)/ 58;

答案 6 :(得分:1)

 double res= (firstIntVar * 100f / secondIntVar) / 100f;

分割数字时我使用 double 或 decimal ,否则我得到 0 ,使用此代码即使 firstIntVar && secondIntVar 是 int 它也会返回预期的答案

相关问题