gpt4 book ai didi

完成我的 addarray () 公式

转载 作者:行者123 更新时间:2023-11-30 17:09:33 25 4
gpt4 key购买 nike

我提前为我的含糊道歉——这是我的第一篇文章,我确实需要一些帮助。

任务如下:

/* 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。

最佳答案

int 是一个保留字。您不能为变量指定名称 int。此外,赋值表示该函数应该采用两个参数,而不是 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;
}

关于完成我的 addarray () 公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33239941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com