c - 矩阵作为函数输入
问题描述
我想构建一个以矩阵作为输入的函数,然后计算所有行(或列)的平均值。我试图这样做,但它给了我一堆错误。
#include <stdio.h>
#include <stdlib.h>
int sum_rows[1000], sum_columns[1000], mean_row[1000], mean_column[1000], N, A[100][100], i, j;
void values(int A[N][N]) {
for (i=0; i<N; ++i) {
for (j=0; j<N; ++j) {
A[i][j] = (rand()%61+20);
}
}
}
void mean_r (int A[N][N]) {
for (i=0; i<N; ++i) {
sum_row[i] = 0;
for (j=0; j<N; ++j) {
sum_row[i] += A[i][j];
}
mean_row[i] = sum_row[i]/N;
}
}
void mean_c (int A[N][N]) {
for (j=0; j<N; ++j) {
sum_column[j] = 0;
for (i=0; i<N; ++i) {
sum_column[j] += A[i][j];
}
mean_column[j] = sum_column[j]/N;
}
}
int main()
{
int N;
printf("Enter size of matrix: ");
scanf("%d", &N);
int A[N][N];
values(A[N][N]);
mean_r(A[N][N]);
mean_c(A[N][N]);
for (i=0; i<N; ++i) {
for (j=0; j<N; ++j) {
printf("A[%d][%d] = %d\n", i, j, A[i][j]);
}
}
for (i=0; i<N; ++i) {
printf("Mean row #%d = %.2f\n", i, mean_row[i]);
}
for (j=0; j<N; ++j) {
printf("Promedio Columna #%d = %.2f\n", j, mean_column[j]);
}
return 0;
}
你能解释一下如何将矩阵传递给函数吗?我必须使用预先定义的函数来执行这些操作,然后在主函数中调用它。
解决方案
您的矩阵似乎是动态的(行数和列数不固定)。在 C 语言中,不允许使用动态行和列声明数组数组,因为编译器不知道如何为您分配多少内存。您必须在运行时分配内存。在我的示例中,矩阵作为第一行、第二行等存储在内存中。在数学中,对矩阵元素的访问是通过行索引和列索引。“行索引和列索引”根据我的示例中矩阵的存储方式,使用分配的内存的起始地址 + 行号 * 列号 + 列索引转换为元素的内存地址。注意:行号和列号都从零开始。第一个元素用 p 表示,其中 p+0*columncount+0) 是 p。下一个元素由 p+0*columncount+1 表示。此后,第二行第二列 (2,2) 的元素由 p+1*column count+1 表示。以下示例使用单个指针来表示动态矩阵(确实存在其他技术,例如指针数组)
在我的示例中,创建并初始化了 3(三行)乘 4(四列)矩阵。ProcessMatrix 函数显示每行的总和。
如果可能的话,我建议你使用 C++,它允许你按照一个整数的值指定的大小来分配内存,这让事情变得更容易。如果您可以访问其他数学库(许多可用),您应该使用它们而不是尝试重新发明轮子。
// c_matrix.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <stdio.h>
int GetElementValue(int* m, int rowIndex, int colIndex, int columnCount)
{
return *(m + (rowIndex * columnCount + colIndex));
}
void ProcessMatric(int* myMatrix, int rowcount, int colcount)
{
// calculate the sum of each row
int sum = 0;
for (int i = 0; i < rowcount; i++)
{
sum = 0;
for (int j = 0; j < colcount; j++)
{
sum = sum + GetElementValue(myMatrix, i, j, colcount);
}
printf("Sum of row %d=%d\r\n", i+1, sum);
}
}
int main()
{
int row = 3;
int col = 4;
int* matrix;
//create the memory for the matrix 3 by 4.
matrix = malloc(sizeof(int) * row * col);
// in momery the matrix is stored as (row1,col1), (row1, col2), (row1,col3)...(row4,col1),(row4,col2),(row4, col3)
// initialize the matrix as 0,1,2,3...11
for (int i = 0; i < row * col; ++i)
{
*(matrix + i) = i;
}
ProcessMatric(matrix, row, col);
free(matrix);
return 0;
}
推荐阅读
- javascript - 如何在兄弟子组件上调用方法或在 reactjs 中向其发送事件
- node.js - 每天摄取数百万个遥测事件 - Redis vs kafka vs 另一个队列/消息代理我最好的摄取
- docker - 在 Docker 代理上使用 Jenkins 管道文件参数
- css - CSS white-space nowrap parent, wrap child
- flask - 图像未在 html 中显示
- html - PowerShell:Measure-Command 向控制台输出漂亮的响应时间列表;当输出到文本文件时,它的一串很长的文本
- python - 读取熊猫上的csv文件时如何解决引号
- c# - 为不同的 Web 项目在 DI 中更改注册的 DbContext,但维护使用它的通用库
- html - -webkit-slider-thumb 高度在 Chrome 上无法正常工作
- android - AAPT:错误:“”与属性 fullBackupContent (attr) 引用不兼容|布尔值