I am learning C# atm and trying to solve one of the problems discribed in my book.
Write a program that calculate and prints (accuracy of 0.001) the sequence 1 + 1/2 – 1/3 + 1/4 – 1/5 + …. I know that this is a common problem, but yet I lost almost a whole day to solve it and yet I can’t do it alone (maybe I am not trying hard enough).
static void Main()
{
double sum = 0D;
double sum1 = 0d;
int i = 1;
while ( i <100)
{
i++;
if (i % 2 == 0)
{
sum1 = sum1 +(1 / i);
}
else
{
sum1 = sum1 -(1 / i);
}
sum = sum1 + sum;
Console.WriteLine(Math.Round(sum, 3));
}
}
Since “i” is an integer, division 1/i will always result in 0 (except the case when i=1) as “/” is an integer division operator and it never gives fractions. So you should divide a double value 1.0/i to get fraction.
In addition the loop condition i<100 isn’t what you need. It is better to set there (1.0/i > 0.001) or transformed (i<1000). For the sequence you have it will guarantee the required accuracy.