完成我的addarray()公式

时间:2015-10-20 14:53:31

标签: c

我提前为我的模糊道歉 - 这是我的第一篇文章,我真的可以使用一些帮助。

作业如下:

/* Write a function named addarray() that returns the sum of the
elements of an array of int values.  Your functions should take two
parameters, the array and the number of elements in the array.  Make
your function work with the following program; */

/* arraysum.c
 * 
 * Synopsis - displays the value returned by the function addarray()
 * with 2 different sets of parameters.
 *
 * Objective - To provide a test program for the addarray() function.
 * Your answers should be 55 and 0.
 *
 */

#include <stdio.h>

int addarray(int [], int, int);

void main() {
    int array1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int array2[4] = {0, 0, 0, 0};

    printf("The sum of array1 = %d\n", addarray(array1, 0, 10));
    printf("The sum of array2 = %d\n", addarray(array2, 0, 4));
}

这是我的解决方案助手:

int addarray(int s[], int i, int n) {
    int sum = 0;
    for (i = 0; i < n; i++) {
        sum += s[i];
    }
    return sum;
}

我似乎无法弄清楚如何获得正确的结果。任何帮助,将不胜感激。 这是我到目前为止所完成的事情:

#include <stdio.h>

int addarray(int array1[], int num_elements);
void print_array(int array1[], int num_elements);

void main(void)
{
   int array1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
   int sum;

   printf("\nArray:\n");
   print_array(array1, 10);

   sum = addarray(array1, 10);
   printf("The sum is %d\n .", sum);
}
int addarray(int array1[], int num_elements)
{
   int i, sum=0;
   for (i=0; i<num_elements; i++)
   {
     sum = sum + array1[i];
   }
   return(sum);
}

void print_array(int array1[], int num_elements)
{
   int i;
   for(i=0; i<num_elements; i++)
   {
     printf("%d ", array1[i]);
   }
   printf("\n");
}

我无法弄清楚如何得到第二个数组来总结。 比如Array2。

1 个答案:

答案 0 :(得分:0)

int是一个保留字。你不能给变量命名int.besides,赋值说该函数应该带两个参数,而不是3.检查这个:

#include <stdio.h>

int addarray(int arr[],int size);

void main() {
  int array1[10] = {1,2,3,4,5,6,7,8,9,10};
  int array2[4] = {0,0,0,0};

  printf("The sum of array1 = %d\n", addarray(array1,10));
  printf("The sum of array2 = %d\n", addarray(array2,4));
}

int addarray(int arr[],int size)
{
    int sum = 0 , n ;
    for( n = 0 ; n < size ; n++ )
    {
        sum += arr[n];
    }
    return sum;
}