// Write a program that inputs positive integer n and prints real number equals to
// 1/0! + 1/1! + 1/2! + … + 1/n!
using System;
using System.Diagnostics;
public class Program
{
public static int InputInt(string prompt)
Console.Write("Enter " + prompt + ":");
return Convert.ToInt32(Console.ReadLine());
}
public static void Main(string[] args)
int n = InputInt("n");
Trace.Assert(n >= 0);
int r = 1;
int i = 0;
double q = 1.0;
// invariant: r = i! and q = 1/0! +...+ 1/i! and 1<=i<=n
while (i != n)
// r = i! and i<n
i = i + 1;
// r = (i - 1)! and q = 1/0! +...+ 1/(i-1)! and i<=n
r = r * i;
// r = (i - 1) * i = i! and q = 1/0! +...+ 1/(i-1)! and i<=n
q = q + 1.0/r;
// r = i! and q = 1/0! +...+ 1/i! and i<=n
// r = n! and q = 1/0! +...+ 1/n!
Console.Write("Sum = " + q);