溫馨提示×

c語言等差數(shù)列求和程序怎么實現(xiàn)

小樊
319
2024-07-26 04:08:10
欄目: 編程語言

下面是一個使用C語言實現(xiàn)等差數(shù)列求和的程序示例:

#include <stdio.h>

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

    // 輸入等差數(shù)列的首項、公差和項數(shù)
    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);

    // 計算等差數(shù)列的和
    sum = n * (2 * firstTerm + (n - 1) * commonDifference) / 2;

    // 輸出結(jié)果
    printf("The sum of the arithmetic sequence is: %d\n", sum);

    return 0;
}

通過輸入等差數(shù)列的首項、公差和項數(shù),該程序?qū)⒂嬎愠龅炔顢?shù)列的和并輸出結(jié)果。

0