C语言 接下来我该怎么做才能在上面创建的汽车索引中找到一个汽车品牌?

km0tfn4u  于 2022-12-03  发布在  其他
关注(0)|答案(1)|浏览(149)
#include <cs50.h>
#include <stdio.h>

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

// print index
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: ");
// prompt user input

// IF else statement
if ((findcar = indexcar[0]))
{
    printf("Volvo\n");
}

else if((findcar = indexcar[1]))
{
    printf("Mazada\n");
}
else if((findcar = indexcar[2]))
{
    printf("Toyota\n");
}
else if((findcar = indexcar[3]))
{
    printf("Tesla\n");
}
else if((findcar = indexcar[4]))
{
    printf("Honda\n");
}
else
{
    printf("Can't find your car brand\n");
}
}

我在代码中做错了什么,在我的汽车索引中查找汽车品牌?当我调试时,我键入的值与我所做的else if语句不同。例如:“Typed:本田,Value = 0x 0980”,“If-else statement value= 08 x2948”,我应该怎么做才能输入汽车品牌,如果该陈述为真,则打印“汽车品牌名称”,如果不是,则打印“找不到您的汽车品牌”?

y0u0uwnf

y0u0uwnf1#

在你的if中,你是在替换值,而不是比较它,把=改为==,就像@艾德·黑尔和@诺达克说的那样。

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

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

// print index
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: ");
// prompt user input

// IF else statement
if ((findcar == indexcar[0])) // note the change from = to ==
{
    printf("Volvo\n");
}

else if((findcar == indexcar[1])) // note the change from = to ==
{
    printf("Mazada\n");
}
else if((findcar == indexcar[2])) // note the change from = to ==
{
    printf("Toyota\n");
}
else if((findcar == indexcar[3])) // note the change from = to ==
{
    printf("Tesla\n");
}
else if((findcar == indexcar[4])) // note the change from = to ==
{
    printf("Honda\n");
}
else
{
    printf("Can't find your car brand\n");
}
}

相关问题