c - 二进制和外部输入的无效操作数

标签 c arrays

我是 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/

相关文章:

c - 链表: Insert function points to itself after second insertion

arrays - MATLAB:从结构数组中收集

javascript - 如何使用日期数组javascript创建计数对象数组

javascript - 如何以不同的方式合并 javascript 中的数组?

c - 用于 C 实现的 Xcode - 随机生成器 - 环境问题

c - 如何使用数学运算符将字符串转换为数字(整数或 float )

c - 丢弃 C 数组中的重复元素/超出数组边界

c++ - 在 C 中打印 unicode 字符

c - 从函数内部使用函数外部定义的数组

arrays - 如何从嵌入字典中的数组中解析 JSON 数据