【发布时间】:2011-05-06 04:47:22
【问题描述】:
我正在尝试解决 Project Euler 的第二个问题,问题是:
斐波那契数列中的每个新项都是通过添加前两项来生成的。从 1 和 2 开始,前 10 个术语将是:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
求序列中所有不超过四百万的偶数项之和。
所以,我设置了以下内容:
using System;
namespace ProjectEuler
{
class Question2
{
//Project Euler - Question 2
//Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
//1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
//Find the sum of all the even-valued terms in the sequence which do not exceed four million
static void Main()
{
int sum = 0;
int oldNumber = 1;
int currentNumber = 1;
int nextNumber;
while (currentNumber <= 500)
{
nextNumber = currentNumber + oldNumber;
if (nextNumber % 2 == 0)
{
sum += currentNumber;
}
}
Console.WriteLine("Project Euler - Question 2\n\nAnswer: " + sum);
Console.ReadLine();
}
}
}
当我运行程序时,没有任何可见的东西,只是 Windows 命令行中的一个光标。我认为这可能是因为 currentNumber 没有得到更新,但我想不出如何正确地做到这一点,即使是这样。
【问题讨论】:
标签: c# if-statement while-loop