c - 使用函数来减少重复性

标签 c for-loop multidimensional-array casting function-definition

我已经研究这个问题有一段时间了:基本上我需要将 for 循环放入一个函数中,以便我可以调用它,但我不知道如何制作一个函数返回一个二维数组,我想通过创建一个一维数组来解决这个问题,但问题是我的任务是计算矩阵对角线下的数字之和,所以我需要它首先是二维的,然后它可以只变成一维。有没有人有解决办法?

也许我的思维过程是错误的,有人可以建议如何将 for 循环放入函数中?如果里面没有 if 子句,那么我可能会有一个想法,但现在我真的没有。

#include <math.h>
#include <stdio.h>
#include <stdlib.h> // libraries added from example
#include <time.h>

//(*) For a square matrix calculate the sum of elements under the main diagonal excluding it.
#define A -10
#define B 10

int main() {
    void enter(int *x, int *y);
    int get_random(int lbound, int ubound); // telling the programs that functions are declared
    int r;
    int c;
    int row, col, sum = 0;
    enter(&r, &c); // calling the function
    srand48(time(NULL)); //Call srand48 with current time reported by `time` casted to a long integer.
    // srand48 is used to reinitialize the most recent 48-bit value in this storage
    int array[r][c]; // we decided its gonna be r rows and c columns
    int line[r * c]; // turning 2d into 1d array
    for (row = 0; row < r; ++row) // we cycle numeration of rows of matrix
    {
        for (col = 0; col < c; col++) // we cycle numeration of columns of matrix
        {
            array[row][col] = get_random(B, A);// filling array with random numbers, taken from example
            printf("%d ", array[row][col]);
            if (row > col) { //since we want the sum numbers below the diagonal row>col must be true
                sum = sum + array[row][col];// if row>col then we add the number to our sum;
            };
        }
        printf("\n"); // this is to break line after row 1,2 col 3, so it looks nicer
    }
    for (row = 0; row < r; ++row) // we cycle numeration of rows of matrix
    {
        for (col = 0; col < c; col++) // we cycle numeration of columns of matrix
        {
            line[row * r + col] = array[row][col];
        }
    }
    printf("the array in 1D: ");
    for (row = 0; row < r * c; row++) {
        printf("%d ", line[row]);
    }
    printf("\n");
    printf("sum of array below the diagonal: %d\n", sum);

    return 0;
}

void enter(int *x, int *y) { // we have to use pointers if we want more then one return from a function

    printf("How man rows in array?  "); // just like the last lab we decide how big the matrix will be
    scanf("%d", x); // we use x instead of &x because we need the address of the number not the value
    printf("How man columns in array? ");
    scanf("%d", y); // we use y instead of &y because we need the address of the number not the value
}

int get_random(int lbound, int ubound) {
    return mrand48() % (ubound - lbound + 1) + lbound; // function for generating random numbers
}

必须满足的条件:

  1. 用户决定方阵的大小

  2. 矩阵必须用随机数填充

  3. 函数调用的数组必须是一维数组,使用i*N+j,不能传递二维数组

最佳答案

让我们考虑一下您的作业

Conditions have to be met:

  1. the user decides size of square matrix

  2. the matrix has to be filled with random numbers

  3. the array is called by the function has to be 1D using i*N+j, 2D array can't be passed

首先矩阵必须是方阵。

这就是你的功能

void enter(int *x, int *y) { // we have to use pointers if we want more then one return from a function

    printf("How man rows in array?  "); // just like the last lab we decide how big the matrix will be
    scanf("%d", x); // we use x instead of &x because we need the address of the number not the value
    printf("How man columns in array? ");
    scanf("%d", y); // we use y instead of &y because we need the address of the number not the value
}

没有意义。用户可以为矩阵的行数和列数输入不同的值。您只需输入一个正值。

其次,当我们谈论矩阵时,这意味着您必须定义一个二维数组。

您还需要编写一个函数来计算矩阵主对角线下元素的总和。该函数的声明方式使其只能接受一维数组。这意味着您需要将矩阵传递给函数,将其转换为 int * 类型的指针。无需创建辅助一维数组,

这是一个演示程序,展示了如何声明和定义函数以及如何将矩阵传递给函数。

#include <stdio.h>

long long int sum_under_dioganal( const int a[], size_t n )
{
    long long int sum = 0;

    for (size_t i = 1; i < n; i++)
    {
        for (size_t j = 0; j < i; j++)
        {
            sum += a[i * n + j];
        }
    }

    return sum;
}

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

    printf( "sum of elements under the main diagonal = %lld\n",
        sum_under_dioganal( ( int * )a, N ) );
}

程序输出为

sum of elements under the main diagonal = 55

定义函数并调用它的另一种方法如下

#include <stdio.h>

long long int sum_under_dioganal( const int a[], size_t n )
{
    long long int sum = 0;

    size_t m = 0;

    while (m * m < n) ++m;

    if (m * m == n)
    {
        for (size_t i = 1; i < m; i++)
        {
            for (size_t j = 0; j < i; j++)
            {
                sum += a[i * m + j];
            }
        }
    }

    return sum;
}

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

    printf( "sum of elements under the main diagonal = %lld\n",
        sum_under_dioganal( ( int * )a, N * N ) );
}

程序输出与上图相同。

sum of elements under the main diagonal = 55

关于c - 使用函数来减少重复性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75297031/

相关文章:

c - 为什么在我的程序中使用条件运算符会给出警告 "pointer/integer type mismatch "?

swift - swift中循环遍历数组问题

java - 具有多个变量的Scala for循环

javascript - “裁剪”二维数组?

ruby - 将字符串转换为 Ruby 中的多维数组?

c - 带参数函数的 printf 返回指向 char 的指针

c - 将结构指针传递给函数时出现段错误

c - postgresql C 输入/输出函数奇怪的行为

objective-c - 如何在 - plist 数组中找到所有值?

algorithm - 当维度可变时遍历 n 维数组