Why do these division equations result in zero?

时光怂恿深爱的人放手 提交于 2019-11-26 11:55:52

You're using int/int, which does everything in integer arithmetic even if you're assigning to a decimal/double/float variable.

Force one of the operands to be of the type you want to use for the arithmetic.

for (int i = 0; i <= 100; i++)
{
    decimal result = i / 100m;
    long result2 = i / 100;
    double result3 = i / 100d;
    float result4 = i / 100f;
    Console.WriteLine("{0}/{1}={2} ({3},{4},{5}, {6})", 
                      i, 100, i / 100d, result, result2, result3, result4);
}

Results:

0/100=0 (0,0,0, 0)
1/100=0.01 (0.01,0,0.01, 0.01)
2/100=0.02 (0.02,0,0.02, 0.02)
3/100=0.03 (0.03,0,0.03, 0.03)
4/100=0.04 (0.04,0,0.04, 0.04)
5/100=0.05 (0.05,0,0.05, 0.05)

(etc)

Note that that isn't showing the exact value represented by the float or the double - you can't represent 0.01 exactly as a float or double, for example. The string formatting is effectively rounding the result. See my article on .NET floating binary point for more information as well as a class which will let you see the exact value of a double.

I haven't bothered using 100L for result2 because the result would always be the same.

Try

i / 100.0

because i is an int: i / 100 performs integer division, then the result, that is always 0, is casted to the target type. You need to specify at least one non-int literal in your expression:

i / 100.0 

Because i is an integer and 100 is an integer...so you have an integer division

Try (decimal)i / 100.0 instead

No matter where you store it, an integer divided by an integer will always be an integer.

You need to force a floating point operation "double / double" instead of an "int / int"

double result = (double)297 / (double)315 ;

this is integer division whatever the type of variable you storing in, so int / int = int

double result3 = ((double)i) / 100;

Because i is a int value and you divide by an integer so the result is an integer ! and so you need to divide by 100.0 to have an implicit cast in float or specify 100f or 100d

In my case I had only vars and no int

float div = (var1 - var2) / float.Parse(var1.ToString());
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!