用c#实现一个等差数组,并输出第n项和前n项的和。
望采纳
可以使用以下代码实现一个等差数组:
using System;
namespace ArithmeticProgression
{
class Program
{
static void Main(string[] args)
{
// 读取用户输入
Console.Write("Enter the first term of the arithmetic progression: ");
int a = int.Parse(Console.ReadLine());
Console.Write("Enter the common difference of the arithmetic progression: ");
int d = int.Parse(Console.ReadLine());
Console.Write("Enter the number of terms in the arithmetic progression: ");
int n = int.Parse(Console.ReadLine());
// 计算第n项
int an = a + (n - 1) * d;
// 计算前n项和
int sum = (n * (2 * a + (n - 1) * d)) / 2;
// 输出结果
Console.WriteLine("The nth term is: " + an);
Console.WriteLine("The sum of the first n terms is: " + sum);
}
}
}