簡體   English   中英

如何將矩陣傳遞給打印它的函數?

[英]How to deliver a matrix to a function that prints it?

我被要求取一個 4x5 的矩陣並掃描每一行(這就是 for 方法的原因),然后打印前半部分,然后打印后半部分。

我相信問題不在函數內部,因為它們在數組上工作正常

當它嘗試打印時,我得到隨機數和零 -

0.000000
-107374176.000000
-107374176.000000
-107374176.000000
-107374176.000000
0.000000
-107374176.000000
-107374176.000000
-107374176.000000
-107374176.000000
0.000000
164582.031250
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
846674930930036512480361854271488.000000
0.000000
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void scanFloats(float** arr, int size); // scans the floats
void printFloats(float* arr, int size); // prints the floats

int main()
{
    float matrix[4][5];

    for (int i = 0; i < 4; i++)
    {
        scanFloats(matrix[i], 5);
    }

    printFloats(matrix, 10);
    printFloats(matrix + 10, 10);
}

void scanFloats(float** arr, int size)
{
    *arr = malloc(sizeof(float) * size);

    for (int i = 0; i < size; i++) {
        printf("Enter number\n");
        scanf("%f", (*arr) + i);
    }
}

void printFloats(float* arr, int size)
{
    for (int i = 0; i < size; i++)
    {
        printf("%f\n", *(arr + i));
    }
}

使用與您的數組相同的類型:

void printFloats(size_t rows, size_t cols, float arr[rows][cols]);

int main(void)
{
    float matrix[4][5] = {
        {1,2,3,4,5},
        {10,20,30,40,50},
        {100,200,300,400,500},
        {1000,2000,3000,4000,5000},
    };

    printFloats( 4, 5, matrix);

}

void printFloats(sizet rows, size_t cols, float arr[rows][cols])
{
    for (size_t r = 0; r < rows; r++)
    {
        for (size_t c = 0; c < cols; c++)
        {

            printf("%8.2f", arr[r][c]);
        }
        printf("\n");
    }
}

與掃描功能相同:

void scanFloats(size_t rows, size_t cols, float arr[rows][cols])
{

    for (size_t r = 0; r < rows; r++)
    {
        for (size_t c = 0; c < cols; c++)
        {
            scanf("%f", &arr[r][c]);
        }
    }
}

https://godbolt.org/z/z8nxo1jhe

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM