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
176 views
in Technique[技术] by (71.8m points)

c# - Why do these division equations result in zero?

The result of all of the division equations in the below for loop is 0. How can I get it to give me a decimal e.g.:

297 / 315 = 0.30793650793650793650793650793651

Code:

using System;

namespace TestDivide
{
    class Program
    {
        static void Main(string[] args)
        {

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

Answer:

Thanks Jon and everyone, this is what I wanted to do:

using System;

namespace TestDivide
{
    class Program
    {
        static void Main(string[] args)
        {
            int maximum = 300;

            for (int i = 0; i <= maximum; i++)
            {
                float percentage = (i / (float)maximum) * 100f;
                Console.WriteLine("on #{0}, {1:#}% finished.", i, percentage);
            }
            Console.ReadLine();
        }
    }
}
Question&Answers:os

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

1 Reply

0 votes
by (71.8m points)

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.


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

...