if you know algebra then you should know thisQuote:
Originally Posted by Zaccheus
c * (a + b) = c * a + c * b;
2 * (3 + 5) = 2 * 3 + 2 *5;
16 = 16 ;
Printable View
if you know algebra then you should know thisQuote:
Originally Posted by Zaccheus
c * (a + b) = c * a + c * b;
2 * (3 + 5) = 2 * 3 + 2 *5;
16 = 16 ;
Indeed.
You are correct, because it is integer division!Quote:
Originally Posted by klamath23
It would wouk if he wrote n / 4.0.
:D
Ah, but you're performing integer division, not floating point division.Quote:
Originally Posted by Zaccheus
6/4 == 1
EDIT: It won't actually be completly accurate if you just change it to 4.0. You may end up with an answer like 11.99999999 instead of 12.
To round a floating point number to the *nearest* integer what you need to do is add 0.5 then just cast the float to int.
i.e.
double result = n * (n / 4.0 + 0.5);
int finalAnswer = (int)(result + 0.5);
Alternatively one of the other forms of the equation would be a better way of doing it.
Well, as it happens 1.5, can be accurately reprepresented in binary - but I do take your point. Rounding errors are always an issue in floating point calculations.
:thumb:
There are better ways to do this problemQuote:
Originally Posted by Zaccheus
like this
Code:int sumEven = 0;
for(int i =2; i<=n;n++)
{
if((i % 2)== 0)
sumEven+=i;
}
Console.WriteLine(" the sum of even numbers till n is:"+sumEven);
You are right. It was just a typo mistake of me because I did not test the code. It means n / 4.0 on that part.Quote:
Originally Posted by Zaccheus
But I am understand the point of view for a rounding error. There is a simple solution. You have only to eliminate the fraction inside.
That's it. There should no rounding error any longer. :wave:Code:public uint Calculate(uint n)
{
//ensure the number is an even number
if (n % 2 == 1)
n -= 1;
//calculate sum without a loop because it is a arithmetic progression
return n*(n + 2) >> 2;
}
thanks for the help but I myself solved it:D