简体   繁体   English

二维数组:C 编程

[英]Two Dimensional Array: C Programming

Can anyone help, I am stuck on solving this question:谁能帮忙,我一直在解决这个问题:

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.用 C 编写一个函数,它接受三个参数: int类型的二维数组的地址、数组中的行数和数组中的列数。 Have the function calculate the sum of the squares of the elements.让函数计算元素的平方和。

For example, for the array of nums that is pictured below:例如,对于下图所示的nums数组:

  23  12  14   3

  31  25  41  17

the call of the function might be sumsquares ( nums, 2, 4 ) ;函数的调用可能是sumsquares ( nums, 2, 4 ) and the value returned would be 4434 .并且返回的值将是4434 Write a short program to test your function.编写一个简短的程序来测试您的功能。


So far my program consists of:到目前为止,我的程序包括:

#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;
}

The answer I am receiving is a huge negative number but it should be 4434.我收到的答案是一个巨大的负数,但应该是 4434。

Any help is greatly appreciated!任何帮助是极大的赞赏!

As you mentioned in question, you need sumsquares( array, 2, 4 );正如您在问题中提到的,您需要sumsquares( array, 2, 4 ); , but your function don't do that. ,但您的功能不这样做。

See below code:见下面的代码:

#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 中创建一个多维数组:

arr = (int **) malloc (( n *sizeof(int *));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM