Write a complete program.
- The program should read two integers: m and n, from the keyboard.
- Allocate memory for a dynamic 2D m * n array of doubles.
- Initialize the array according to the formula
A[i][j]=(i-5)/(j+1)
.
我的代码:
#include <stdio.h>
#include <math.h>
int main() {
int m,n;
scanf ("%d %d",&m &n);
double**A=(double**) malloc (m*size of (double*));
double*B=(double*) malloc (m*n * size of (double));
for (int i=0;i<n;i++){
A[i]=B+i*m;
}
for (int i=0;i<n;i++){
for (int j=0;i<m;j++){
A[i][j]=(i-5)/(j+1);
}
}
free (A);
free (B);
return 0;
}
最佳答案
有一些错误:
-
size
未定义。 -
#include <math.h>
不需要,因为您不调用任何数学函数。 - 严格来说你应该
#include <stdlib.h>
正如声明malloc()
和 friend 们。 - 一个
,
scanf ("%d %d",&m &n);
中缺失. - 无需转换
malloc()
返回值。 - 变量名称始终以小写字母开头。
- 您有一个
}
太多了。 - 缩进和代码格式确实很糟糕,而且是自找麻烦。**
- ...
检查this section of the C-FAQ查看您是否正确完成了分配。
想法:仔细阅读上面提到的 C-FAQ,它会教给您很多知识,并且会成为宝贵的时间投资。
**这是一个良好的代码缩进和格式设置的示例(没有修复):
int main()
{
int m;
int n;
scanf("%d %d", &m, &n);
double** A = malloc(m * size of (double*));
double* B = malloc(m * n * size of (double));
for (int i = 0; i < n; i++)
{
B[i] = B + i * m;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; i < m; j++)
{
A[i][j] = (i - 5) / (j + 1);
}
}
free(A);
free(B);
return 0;
}
好吧,我修复了多余的}
.
关于c - C语言代码的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48242807/