gpt4 book ai didi

c - 二维数组: C Programming

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

谁能帮忙,我一直在解决这个问题:

Write a function in C that takes three parameters: the address of a two dimensional array of type int, the number of rows in the array, and the number of columns in the array. Have the function calculate the sum of the squares of the elements.

例如,对于下图所示的 nums 数组:

  23  12  14   3

31 25 41 17

函数的调用可能是sumsquares (nums, 2, 4);返回的值将是 4434。编写一个简短的程序来测试您的功能。

<小时/>

到目前为止,我的程序包括:

#include<stdio.h>
int addarrayA(int arrayA[],int highestvalueA);

int addarrayA(int arrayA[],int highestvalueA)
{
int sum=0, i;
for (i=1; i<highestvalueA; i++)
sum = (i*i);

return sum;
}

int main( void )
{
int arr [2][4] = {{ 23, 12, 14, 3 },
{ 31, 25, 41, 17 }};

printf( "The sum of the squares: %d. \n", addarrayA (arr[2], arr[4]) );

return 0;
}

我收到的答案是一个巨大的负数,但它应该是 4434。

非常感谢任何帮助!

最佳答案

正如您在问题中提到的,您需要 sumsquares( array, 2, 4 ); ,但您的函数不会这样做。

参见下面的代码:

#include<stdio.h>

int sumsquares(int* arrayA,int row, int column);

int sumsquares(int* arrayA,int row, int column)
{
int sum=0, i;
for (i=0; i<row*column; i++)
sum += (arrayA[i]*arrayA[i]);

return sum;
}

int main( void )
{
int arr [2][4] = {{ 23, 12, 14, 3 },
{ 31, 25, 41, 17 }};

printf( "The sum of the squares: %d. \n", sumsquares (&arr[0][0], 2, 4) );

return 0;
}

Output:

The sum of the squares: 4434.

关于c - 二维数组: C Programming,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34079633/

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