【发布时间】:2011-12-23 22:34:44
【问题描述】:
我仍然是 C 编程的初学者,我需要一些帮助来为我的 C 编程课程编写代码。
提示是:该程序的输入是一个二维浮点数据数组,位于名为 textfile94 的文件中。输入数组将包含 3 行数据,每行包含 5 列数据。
- 我要你用动态内存的二下标法 分配。
- 使用 malloc 创建一个包含指针的数组。
- 该数组的每个元素都指向另一个数组,即数据行。
- 在循环中使用 malloc 来创建行。
- 然后您可以使用两个下标运算符 [r][c] 来获取您的数据 进行程序要求的求和和平均。
- 此程序要求对二维数组的高度和宽度进行硬编码, 提前知道(实际上是 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;
}
【问题讨论】: