C中n个数字的总和
2021-07-06 22:00:33
深夜i
--
--
C
中
n
个
数
字
的
总
和
C 中 n 个数字的总和:该程序将用户输入的 n 个数字相加。 用户输入一个数字,指示要添加多少个数字和 n 个数字。 我们可以通过使用数组和不使用数组来做到这一点。
C程序使用for循环查找n个数字的总和
#include <stdio.h>
int main()
{
int n, sum = 0, c, value;
printf("How many numbers you want to add?\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 1; c <= n; c++)
{
scanf("%d", &value);
sum = sum + value;
}
printf("Sum of the integers = %d\n", sum);
return 0;
}
您可以对变量 sum 使用 long int 或 long long 数据类型。下载添加 n 个数字程序。
程序输出:
C程序使用数组查找n个数字的总和
#include <stdio.h>
int main()
{
int n, sum = 0, c, array[100];
scanf("%d", &n);
for (c = 0; c < n; c++)
{
scanf("%d", &array[c]);
sum = sum + array[c];
}
printf("Sum = %d\n", sum);
return 0;
}
使用数组的优点是我们有输入数字的记录,如果需要,可以在程序中进一步使用它们,但存储它们需要额外的内存。
使用递归将 n 个数字相加的 C 程序
#include <stdio.h>
long calculate_sum(int [], int);
int main()
{
int n, c, array[100];
long result;
scanf("%d", &n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
result = calculate_sum(array, n);
printf("Sum = %ld\n", result);
return 0;
}
long calculate_sum(int a[], int n) {
static long sum = 0;
if (n == 0)
return sum;
sum = sum + a[n-1];
return calculate_sum(a, --n);
}
上一篇:
idea打包java可执行jar包
下一篇:
C程序交换两个数字
评论区