我是 C 语言的初学者。我有这段代码。我在从 external.txt 文件扫描输入时遇到问题。 这样写:
30.5(tab)20.5(\n or newline)
22.5(tab)3.65(\n or newline)
./prog.out < external.txt in compiling
<小时/>
#include<stdio.h>
#define LEN 2
int main()
{
float array[2][2];
int i;
int j;
float sum;
printf("Input 2X2 array:");
for (i=0; i<LEN; i++){
for (j=0; j<LEN; i++){
scanf("%f ", &array[i][j]);
}
}
//average of row
for( i=0; i<LEN; i++){
printf("row index %d:\t%f\n", i, array[i]);
sum = sum + array[i];
printf( "Average: %f\n", (float)sum / LEN );
}
return 0;
我有这个错误;
警告:格式“%f”需要“double”类型的参数,但参数 3 的类型为“float *”[-Wformat]
:19:13: 错误:sum=sum+array[i] 中的二进制 + 操作数无效(具有“float”和“float *”)
最佳答案
scanf("%f ", &array[i][j]);
格式 %f 并不是为了捕获“ float ”。这是为了“双”。 您需要 array[i][j] 是“double”类型的对象。 您可以执行以下两项操作之一:
- 将数组类型更改为
double a[2][2]
。 - 或者,声明一个临时 double 变量以在
scanf()
语句中使用,然后将获得的值赋给a[i][j]
。
代码:
printf("Input 2X2 array:");
double temp;
for (i=0; i<LEN; i++){
for (j=0; j<LEN; i++){
scanf("%f ", &temp);
a[i][j] = temp;
}
}
在程序的第二部分中,您的逻辑错误,因为您必须获得每行的平均值。你不能像数学那样对行求和。在 C 中,您必须为每一行手动求和。因此,您需要再次迭代数组的子索引。
不管怎样,我相信你得重新思考一下问题的逻辑。
这不仅仅是C语法的问题。
关于c - 二进制和外部输入的无效操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21292742/