为什么这些除法方程得出零?

下面for循环中所有除法方程式的结果均为0。如何获取小数,例如:


297 / 315 = 0.30793650793650793650793650793651

码:


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();

        }

    }

}

回答:

感谢Jon和所有人,这就是我想要做的:


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();

        }

    }

}


一只斗牛犬
浏览 691回答 4
4回答

哆啦的时光机

您正在使用int / int,即使您要分配给十进制/双精度/浮点型变量,它也会以整数算术执行所有操作。强制其中一个操作数为您要用于算术的类型。for (int i = 0; i <= 100; i++){&nbsp; &nbsp; decimal result = i / 100m;&nbsp; &nbsp; long result2 = i / 100;&nbsp; &nbsp; double result3 = i / 100d;&nbsp; &nbsp; float result4 = i / 100f;&nbsp; &nbsp; Console.WriteLine("{0}/{1}={2} ({3},{4},{5}, {6})",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i, 100, i / 100d, result, result2, result3, result4);}结果: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)(等等)请注意,这并没有显示由float或double表示的确切值-例如,您不能将0.01精确地表示为float或double。字符串格式有效地舍入了结果。见我在.NET上的文章浮动小数点的更多信息,以及为一类,这将让你看到确切的双重价值。我没有result2因为使用100L而烦恼,因为结果总是一样的。

牧羊人nacy

因为i是INT:i / 100执行整数除法,那么结果,即总为0,浇铸到目标类型。您需要在表达式中至少指定一个非整数文字:i / 100.0&nbsp;

萧十郎

因为我是一个整数而100是一个整数...所以你有一个整数除法尝试使用(十进制)i / 100.0

小怪兽爱吃肉

您需要强制执行浮点运算“ double / double”而不是“ int / int”double result = (double)297 / (double)315 ;
打开App,查看更多内容
随时随地看视频慕课网APP