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

C语言读取txt文件数据存入二维数组后基因匹配失败问题求助

问题排查与修正

1. 核心错误说明

  • 文件读取逻辑错误:你在外层循环中多写了一行多余的fscanf(dnaFile, " %f", criminals[i]);,这行代码会提前读取每行的第一个浮点数据,导致后续内层循环读取的10个数据整体错位,criminals数组存储的内容和txt文件实际内容完全不符。
  • 匹配逻辑错误:当前循环嵌套顺序写反,判断逻辑也不符合需求:现有逻辑要求嫌疑人的第i个数据,要和所有罪犯的第i行第j个数据都相等,和你要的「某一行罪犯数据和嫌疑人10个数据完全一致」的需求完全不符。
  • 浮点数判断精度问题:浮点数存储存在精度误差,直接用!=或者==判断两个浮点数相等是错误写法,应该判断两个数的差的绝对值小于极小阈值(比如1e-6)来判定相等。

2. 优化补充点

  • 需要增加文件打开失败的判断,避免文件不存在时程序崩溃
  • 文件读取完成后要调用fclose释放资源

3. 修正后完整代码

#include <stdio.h>
#include <stdbool.h>
#include <math.h> // 用于浮点数绝对值计算函数fabs

// 定义浮点数相等判断的精度阈值
#define EPS 1e-6

int main(){
    FILE *dnaFile = fopen("dnaInput.txt", "r");
    // 新增文件打开失败判断
    if (dnaFile == NULL) {
        printf("文件打开失败,请确认dnaInput.txt路径正确\n");
        return 1;
    }

    const int size = 10;
    float suspect[size];

    const int sizeR = 6;
    const int sizeC = 10;
    float criminals[sizeR][sizeC];

    printf("\nEnter the 10 chromosomes of the suspect seperated by spaces: \n");
    for (int i = 0; i < size; i++) {
        scanf(" %f", &suspect[i]);
    }

    // 修正读取逻辑:删除多余的fscanf
    for (int i = 0; i < sizeR; i++) {
        for (int j = 0; j < sizeC; j++) {
            fscanf(dnaFile, " %f", &criminals[i][j]);
        }
    }
    fclose(dnaFile); // 读取完成后关闭文件释放资源

    bool match = false;
    // 修正匹配逻辑:逐行比对罪犯数据
    for (int i = 0; i < sizeR; i++) { // 遍历所有罪犯的基因序列
        bool curMatch = true;
        for (int j = 0; j < sizeC; j++) { // 比对当前序列的每个位置
            if (fabs(suspect[j] - criminals[i][j]) > EPS) {
                curMatch = false;
                break; // 有一个位置不匹配就跳过当前序列
            }
        }
        if (curMatch) {
            match = true;
            break; // 找到匹配序列直接跳出所有循环
        }
    }

    if (match)
        printf("\nSuccess: A match was found! \n");
    else
        printf("\nFailure: No match was found \n");

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 14:06:04