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

1633
2024/8/12 13:24:52
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

下面是一个使用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;
}

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

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c语言strcmp函数的用法是什么