我还是一个C编程的初学者,需要在我的C编程课上写代码,希望你能给我一些帮助。
任务是:输入数据来自名为textfile94的文件中包含浮点数据类型的二维数组。输入的数组将包含3行数据,每行都包含5列数据。
- 我希望您使用两个下标的动态内存分配方法。
- 使用malloc创建一个保存指针的数组。
- 该数组的每个元素指向另一个数组,即数据行。
- 使用循环中的malloc创建您的行。
- 然后,您可以使用两个下标操作符[r][c]来获取您的数据,进行求和和平均。
- 该程序要求硬编码2D数组的高度和宽度,这些事先已知(实际上是3x5)。
- 在您的代码中不要写入文字数字,而是创建一个全局常量变量来保存这些维度,并在您的代码中使用它们。
下面是我的代码:
#include <stdio.h>
#include <stdlib.h>
#define int rows = 3;
#define int columns = 5;
float array[rows][columns];
int main(int argc, char* argv[]){
FILE* fin;
float x;
int i,j;
int* array;
fin = fopen("textfile94", "r");
fscanf(fin,"%f", &x);
array =(int*) malloc(rows* sizeof(int*));
for(i=0;i<rows;i++){
for(j=0;j<columns;j++)
array[i]=(int*)malloc(columns* sizeof(int));
}
printf("The Average values for the three rows are:[%f]",array[i]);
printf("The Average values for the five columns are:[%f]", array[j]);
return 0;
}
在文本文件中: 4.33 5.33 1.11 99.00 100.00 1.0 33.3 12.5 1.1 -1000.00 22.1 11.9 2.4 8.3 8.9
程序应该输出: 三行的平均值为:41.95 -190.42 10.32 五列的平均值为:9.14 16.84 5.33 36.13 -297.7
遇到问题无法正确完成,任何帮助将不胜感激。我不想要答案,我想从中学习,只需要一些提示。谢谢。
更新后的代码:
#include <stdio.h>
#include <stdlib.h>
#define ROWS 3
#define COLUMNS 5
float array[ROWS][COLUMNS];
int main(int argc, char* argv[]){
FILE* fin;
int i;
float x;
float** array;
fin = fopen("textfile94", "r");
array=(float**) malloc(ROWS*sizeof(float*));
for(i=0;i<ROWS;i++)
array[ROWS]=(float*)malloc(COLUMNS*sizeof(float));
for(j=0;j<COLUMNS;j++){
fscanf(fin,"%f",&x);
x = array[ROWS][COLUMNS];
}
printf("The Average values for the three rows are:%f", array[ROWS]);
printf("The Average values for the five columns are:%f", array[COLUMNS]);
return 0;
}