输入一个数,输入n为偶数时,求1/2+1/4+...+1/n,当输入n为奇数时,1/1+1/3+...+1/n
输入一个数,输入n为偶数时,求1/2+1/4+...+1/n,当输入n为奇数时,1/1+1/3+...+1/nstatic void Main(string[] args) { Func<double, double> round = d => Math.Round(d, 10); IDictionary<int, double> theoreticalValues = new Dictionary<int, double> { {1, 1.0}, {2, 1.0/2}, {3, 1.0 + 1.0/3}, {4, 1.0/2 + 1.0/4}, {5, 1.0 + 1.0/3 + 1.0/5}, {6, 1.0/2 + 1.0/4 + 1.0/6}, {7, 1.0 + 1.0/3 + 1.0/5 + 1.0/7}, {8, 1.0/2 + 1.0/4 + 1.0/6 + 1.0/8}, {9, 1.0 + 1.0/3 + 1.0/5 + 1.0/7 + 1.0/9}, {10, 1.0/2 + 1.0/4 + 1.0/6 + 1.0/8 + 1.0/10} }; Console.WriteLine("Expected\t| Computed\t| Result\n"); foreach (var pair in theoreticalValues) { double sum = 0.0; int n = pair.Key; int i = n % 2 == 0 ? 2 : 1; while (i <= n) { sum += 1.0 / i; i += 2; }; Console.WriteLine("{0:#0.0000000000}\t| {1:#0.0000000000}\t| {2}\n", round(pair.Value), round(sum), (round(pair.Value) - round(sum) == 0) ? "Passed" : "Failed"); } }