0

This algorithm works in C++, but in C# gives as result 0 everytime. What is wrong there ?

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

The problem is as follows (1+1)/(1+2) + (2+1)/(2+2) + ... + (10+1)/(10+2)

2 Answers2

1

It's most likely a case of integer division: x/y = 0 when x < y. Make those values floating point numbers and it'll work fine.

Try this:

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); 
        } 
    } 
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
0

The only issue is when your algorithm is doing integer division. Put ( i + 1.0 )

Nadhir Houari
  • 390
  • 4
  • 10