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

C语言客户ID查询程序未匹配时输出0而非-1如何修复

问题根源

  • count数组为局部变量,未手动初始化,存储的是随机垃圾值,无法作为「是否找到匹配ID」的判断依据
  • 没有提前给所有查询对应的count标记为「未找到」的初始状态,导致未匹配到的ID对应的count值是随机数,判断条件失效

修复步骤

  1. 读取查询次数x后,先初始化所有count[j]为1,代表默认未找到匹配ID
scanf("%d",&x);
// 新增初始化代码
for(j=0; j<x; j++){
    count[j] = 1;
}
  1. 原有匹配逻辑保持不变,匹配到ID时将对应count[j]设为0即可

修复后完整代码

#include <stdio.h>
#include <string.h>

struct Customer{
    char ID[100];
    char name[100];
    int age;
    double balance;
}N[1000];

int main(){
    int n,i,x,j,b[100],count[100];
    char m[100][100];
    char a[100][100];
    double c[100];
    
    scanf("%d",&n);
    getchar();
    
    for(i=0; i<n; i++){
        scanf(" %[^,],%[^,],%d,%lf",N[i].ID,N[i].name,&N[i].age,&N[i].balance);
        getchar();
    }
    scanf("%d",&x);
    // 新增count数组初始化
    for(j=0; j<x; j++){
        count[j] = 1;
    }
    for(i=0; i<x; i++){
        scanf("%s",m[i]);
        getchar();
    }
    for(i=0; i<n; i++){
        for(j=0; j<x; j++){
            if(strcmp(m[j],N[i].ID) == 0){
                strcpy(a[j],N[i].name);
                b[j] = N[i].age;
                c[j] = N[i].balance;
                count[j] = 0;
            }   
        }
    }
    for(i=0; i<x; i++){
        if(count[i] == 0){
            printf("%s %d %.2lf\n",a[i],b[i],c[i]);
        }
        else{
            printf("-1\n");
        }
    }
    
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:36:00