正确的算法在C#中返回错误的结果

时间:2018-02-21 12:02:15

标签: c# math

此算法适用于C ++,但在C#中每次都给出结果为0。有什么问题?

using System;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            double sum = 0;
            for(int i=1; i <= 10; i++)
            {
                sum += (i+1)/(i+2);  
            }
            Console.WriteLine("{0}", sum);
        }
    }
}

问题如下(1 + 1)/(1 + 2)+(2 + 1)/(2 + 2)+ ... +(10 + 1)/(10 + 2)

2 个答案:

答案 0 :(得分:1)

这很可能是整数除法的情况:当x <0时,x / y = 0。年。将这些值设为浮点数,它将正常工作。

试试这个:

using System;

namespace Rextester { 
    public class Program { 
        public static void Main(string[] args) { 
            double sum = 0.0; 
            for(int i=1; i <= 10; i++) { 
                sum += (i+1.0)/(i+2.0);  // 1.0 instead of 1 will tell the compiler to use floating point division.
            } 
            Console.WriteLine("{0}", sum); 
        } 
    } 
}

答案 1 :(得分:0)

唯一的问题是你的算法进行整数除法。放(i + 1.0)