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

汽车品牌索引查找代码错误排查及正确实现方法

代码错误分析与修复方案

存在的错误

  • 错误1:误用赋值运算符:所有if/else if条件中使用了赋值运算符=,而非用于比较的==。findcar = indexcar[0]是将数组元素的地址赋值给findcar,这个表达式的值永远非零(地址有效),导致第一个if永远成立,直接输出"Volvo",后续判断完全不会执行。
  • 错误2:直接比较字符串内存地址:数组中的汽车品牌是字符串字面量,存储在程序的只读数据段;而get_string获取的用户输入是在堆上动态分配的新内存,两者内存地址必然不同。直接通过地址相等判断字符串内容一致是完全错误的,必须通过字符串内容比较函数来判断。
  • 拼写小问题:原代码中"Mazada"拼写错误,应为"Mazda",会导致用户输入正确名称时无法匹配。

修复后的代码

需要引入<string.h>头文件以使用字符串比较函数strcmp,同时修正条件判断逻辑,示例如下:

#include <cs50.h>
#include <stdio.h>
#include <string.h> // 引入字符串处理头文件

int main (void)
{
    string indexcar[5];
    indexcar[0] = "Volvo";
    indexcar[1] = "Mazda";
    indexcar[2] = "Toyota";
    indexcar[3] = "Tesla";
    indexcar[4] = "Honda";

    // 打印索引
    printf("Car index included:\n");
    printf("%s\n", indexcar[0]);
    printf("%s\n", indexcar[1]);
    printf("%s\n", indexcar[2]);
    printf("%s\n", indexcar[3]);
    printf("%s\n", indexcar[4]);

    string findcar = get_string("Car brand to find: ");

    // 查找逻辑
    if (strcmp(findcar, indexcar[0]) == 0)
    {
        printf("Volvo\n");
    }
    else if(strcmp(findcar, indexcar[1]) == 0)
    {
        printf("Mazda\n");
    }
    else if(strcmp(findcar, indexcar[2]) == 0)
    {
        printf("Toyota\n");
    }
    else if(strcmp(findcar, indexcar[3]) == 0)
    {
        printf("Tesla\n");
    }
    else if(strcmp(findcar, indexcar[4]) == 0)
    {
        printf("Honda\n");
    }
    else
    {
        printf("无法找到您的汽车品牌\n");
    }
}

额外优化建议

用循环简化重复的判断逻辑,让代码更简洁易维护:

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

int main (void)
{
    string indexcar[5] = {"Volvo", "Mazda", "Toyota", "Tesla", "Honda"};

    printf("Car index included:\n");
    for (int i = 0; i < 5; i++) {
        printf("%s\n", indexcar[i]);
    }

    string findcar = get_string("Car brand to find: ");
    int found = 0;

    for (int i = 0; i < 5; i++) {
        if (strcmp(findcar, indexcar[i]) == 0) {
            printf("%s\n", indexcar[i]);
            found = 1;
            break;
        }
    }

    if (!found) {
        printf("无法找到您的汽车品牌\n");
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:50:44