You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言代码报Invalid operands to binary expression错误求助

错误原因

你报错行的criminals[i]对应的类型是float [sizeC](长度为10的浮点数数组),而suspect[i]的类型是float(单个浮点数),两种完全不同的类型不能直接用!=运算符做比较,所以编译器抛出了invalid operands to binary expression的错误。

修复逻辑
  • 你的criminals是二维数组,存储了3个罪犯的染色体数据,所以需要先遍历每一个罪犯,再逐个比对10条染色体的数值
  • 浮点数存在精度存储误差,不能直接用==/!=判等,要通过判断两个数值的差值是否小于一个极小的阈值(比如1e-6)来确认是否相等
  • 用宏定义常量代替变量定义数组长度兼容性更好,可避免可变长度数组(C99特性)的兼容问题
修复后的完整代码
#include <stdio.h>
#include <stdbool.h>
#include <math.h> // 用于调用fabs求浮点数绝对值

#define SIZE 10       // 染色体条数
#define SIZER 3       // 罪犯人数
#define EPS 1e-6      // 浮点数比较的误差阈值

int main(){
    float suspect[SIZE];
    float criminals[SIZER][SIZE];

    // 读取嫌疑人染色体数据
    printf("Enter the 10 chromosomes of the suspect separated by spaces: \n");
    for (int i = 0; i < SIZE; i++)
        scanf(" %f", &suspect[i]);

    // 读取3名罪犯的染色体数据
    for (int i = 0; i < SIZER; i++){
        printf("Enter the 10 chromosomes of the %dth criminal: \n", i+1);
        for (int j = 0; j < SIZE; j++)
            scanf(" %f", &criminals[i][j]);
    }

    // 匹配逻辑
    bool matched = false;
    int matched_index = -1;
    // 遍历每个罪犯
    for (int k = 0; k < SIZER; k++) {
        bool current_match = true;
        // 比对每条染色体
        for (int i = 0; i < SIZE; i++) {
            if(fabs(suspect[i] - criminals[k][i]) > EPS) {
                current_match = false;
                break; // 单条不匹配就终止当前罪犯的比对
            }
        }
        if(current_match) {
            matched = true;
            matched_index = k+1;
            break;
        }
    }

    // 输出结果
    if (matched)
        printf("The suspect matches the %dth criminal! \n", matched_index);
    else
        printf("The suspect doesn't match any criminal in the database! \n");

    return 0;
}

如果你的需求只是比对指定位置的某一个罪犯,比如第一个罪犯,不需要遍历所有罪犯,直接把原错误行的criminals[i]修改为criminals[0][i]即可修复编译错误。
引入math.h后编译时需要链接数学库,用gcc编译的指令为gcc test.c -o test -lm。

内容的提问来源于stack exchange,提问作者user17221554

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:06:04