-1

I am trying to solve the Project Euler problem number 6 with the following program:

double counter = 1;
double sumsquare = 0;
double squaresum = 0;
while (counter <= 100)
{
  sumsquare += Math.Pow(counter, 2);
  squaresum += counter;
  counter++;
}
Math.Pow(squaresum, 2);
Console.WriteLine("the sum is {0} ,the square is :{1}", squaresum.ToString(), sumsquare.ToString());
double diff = sumsquare - squaresum;
Console.WriteLine(diff.ToString());
Console.ReadLine();

However, the answer was wrong. Can anyone tell me what the problem is with my code?

4

2 回答 2

4

你有一个错误,你正在计算一个幂然后丢弃它。

更一般地说,在解决涉及整数的 PE 问题时,您应该避免使用 double。双打只精确到小数点后十五位;在那之后,他们四舍五入。

更好的类型是long,它可以表示最大为 9,223,372,036,854,775,807 的整数或 decimal,它可以表示最大为 79,228,162,514,264,337,593,543,950,335 的整数,或者 BigInteger,它可以表示任意大的值。

请注意,当您使用越来越大的类型时,代码通常会变慢。

更一般地说,现在是学习如何使用调试器的好时机。找出您可以手动计算的非常小的情况下程序的输出应该是什么。然后逐行检查你的程序,看看哪里出错了。这是一种比询问互联网更有效的调试问题的方法。

于 2013-02-10T15:36:12.323 回答
3

You seem to think that Math.Pow(squaresum, 2); modifies squaresum. That's not so: it returns a square of squaresum, and you should assign it to squaresum if you want the variable to be modified.

squaresum = Math.Pow(squaresum, 2);

Also the idea of using double type here is not quite good, but it appears that you won't lose enough precision here to get a wrong result.

于 2013-02-10T15:34:58.647 回答