c语言

c语言等差数列求和程序怎么实现

小樊
127
2024-07-26 04:08:10
栏目: 编程语言

下面是一个使用C语言实现等差数列求和的程序示例:

#include <stdio.h>

int main() {
    int firstTerm, commonDifference, n, sum = 0;

    // 输入等差数列的首项、公差和项数
    printf("Enter the first term of the arithmetic sequence: ");
    scanf("%d", &firstTerm);
    printf("Enter the common difference of the arithmetic sequence: ");
    scanf("%d", &commonDifference);
    printf("Enter the number of terms in the arithmetic sequence: ");
    scanf("%d", &n);

    // 计算等差数列的和
    sum = n * (2 * firstTerm + (n - 1) * commonDifference) / 2;

    // 输出结果
    printf("The sum of the arithmetic sequence is: %d\n", sum);

    return 0;
}

通过输入等差数列的首项、公差和项数,该程序将计算出等差数列的和并输出结果。

0
看了该问题的人还看了