求等差数列之和的C程序
问题
找出一个等差数列系列的总和,其中用户必须输入第一个数字、元素总数和公差。
解决方案
算术级数 (AP) 是一系列数字,其中任何两个连续数字的差总是相同的。这里,元素的总数被称为Tn。
Sum of A.P. Series: Sn = n/2(2a + (n – 1) d)Tn term of A.P. Series: Tn = a + (n – 1) d
算法
参考下面给出的算法来找到等差数列。
Step 1: Declare variables.Step 2: Initialize sum=0
Step 3: Enter first number of series at runtime.
Step 4: Enter total number of series at runtime.
Step 5: Enter the common difference at runtime.
Step 6: Compute sum by using the formula given below.
sum = (num * (2 * a + (num - 1) * diff)) / 2
Step 7: Compute tn by using the formula given below.
tn = a + (num - 1) * diff
Step 8: For loop
i = a; i <= tn; i = i + diff
i. if(i != tn)
printf("%d + ", i);
ii. Else,
printf("%d = %d", i, sum);
Step 9: Print new line
程序
以下是计算等差数列之和的 C 程序 -
#include <stdio.h>输出结果int main() {
int a, num, diff, tn, i;
int sum = 0;
printf(" 输入第一个系列: ");
scanf("%d", &a);
printf(" enter total no's in series: ");
scanf("%d", &num);
printf("输入共同差异: ");
scanf("%d", &diff);
sum = (num * (2 * a + (num - 1) * diff)) / 2;
tn = a + (num - 1) * diff;
printf("\n sum ofA.Pseries is : ");
for(i = a; i <= tn; i = i + diff){
if(i != tn)
printf("%d + ", i);
else
printf("%d = %d", i, sum);
}
printf("\n");
return 0;
}
执行上述程序时,会产生以下结果 -
输入第一个系列: 3enter total no's in series: 10
输入共同差异: 5
sum ofA.Pseries is: 3 + 8 + 13 + 18 + 23 + 28 + 33 + 38 + 43 + 48 = 255
输入第一个系列: 2
enter total no's in series: 15
输入共同差异: 10
sum ofA.Pseries is: 2 + 12 + 22 + 32 + 42 + 52 + 62 + 72 + 82 + 92 + 102 + 112 + 122 + 132 + 142 = 1080
以上是 求等差数列之和的C程序 的全部内容, 来源链接: utcz.com/z/327566.html