给定数列的前n项和
#include <stdio.h>
#include <stdlib.h>
/*
*功能:
-
参数列表:
-
返回值:
/
int sum(int numbers, int size, int n);
void printInfo(int* number, int size, int n, int ret);
int main()
{
srand(time(NULL));int nums[] = { 1,5,9,20,48,6,86,34,91 };
int size = sizeof(nums) / sizeof(int);
int n = 5;
int ret = sum(nums, size, n);
printInfo(nums, size, n, ret);
return 0;
}
int sum(int* numbers, int size, int n)
{
if (n > size)
{
n = size;
}
int ret = 0;
for (int i = 0; i < n; ++i)
{
ret += numbers[i];
}
return ret;
}
void printInfo(int* number, int size, int n, int ret)
{
printf(“数列:”);
for (int i = 0; i < size; ++i)
{
printf("%d ", number[i]);
}
printf(“的前%d项之和 = %d”, n, ret);
}