【问题标题】:How to scan through all "else if" conditions - C如何扫描所有“else if”条件 - C
【发布时间】:2017-03-10 21:00:03
【问题描述】:

对于我的 C 作业,我需要输入捐款金额、输入请求并完成请求。基本上我有一个名为 donType[i] 的数组,其中 i 的范围是 0 到 4。donType[0] 代表蛋白质请求,donType[1] 代表乳制品请求,dontype[2] 代表谷物请求,依此类推,您将在我的代码。如果任何捐赠类型的库存为 0(意味着没有捐赠被添加到数组的值中),那么我希望它打印“类型捐赠无法完成”,其中 type 表示食物的类型(蛋白质、乳制品、谷物等)。如果我将所有库存设置为 0,它只会打印“无法满足蛋白质请求”,它应该打印所有无法满足的请求。这是我的代码的一部分:

        if (donType[0] == 0) 
            printf("Protein requests cannot be fulfilled.\n");
        else if (donType[1] == 0)
            printf("Dairy requests cannot be fulfilled.\n");
        else if(donType[2] == 0)
            printf("Grain requests cannot be fulfilled.\n");
        else if (donType[3] == 0)
            printf("Vegetable requests cannot be fulfilled.\n");
        else if (donType[4] == 0)
            printf("Fruit requests cannot be fulfilled.\n");

所以它在扫描到 donType[0] 等于 0 后停止。如何让我的代码继续扫描 else if 语句?请记住,我是这方面的新手,所以我不需要任何复杂的答案。感谢您的帮助!

【问题讨论】:

  • 您可能想了解if 语句及其工作原理。不清楚你的问题是什么。请参阅How to Ask 并提供minimal reproducible example
  • 取出所有else
  • if 主体周围的大括号阻止代码编译(第一个 else 没有匹配的 if)。您可能应该使用循环而不是写出几乎相同的代码 5 次。您可以有一组捐赠类型名称:char *donTypeName[] = { "Protein", "Dairy", "Grain", "Vegetable", "Fruit" };for (int i = 0; i < 5; i++) { if (donType[i] == 0) printf("%s requests cannot be fulfilled\n", donTypeName[i]); } 或类似的名称。
  • 谢谢乔纳森,我不小心在那儿添加了大括号(不知道为什么)。我更正了帖子中的问题。我还将按照您的建议使用循环重写我的代码。

标签: c arrays conditional


【解决方案1】:

条件不是互斥的,所以只要去掉else关键字,它们都是独立的if语句。

【讨论】:

  • 为什么这被否决了?很短,但它是正确的。
【解决方案2】:

您需要将 else if 语句替换为 if 语句

if (donType[0] == 0) 
    printf("Protein requests cannot be fulfilled.\n");
if (donType[1] == 0)
    printf("Dairy requests cannot be fulfilled.\n");
if(donType[2] == 0)
    printf("Grain requests cannot be fulfilled.\n");
if (donType[3] == 0)
    printf("Vegetable requests cannot be fulfilled.\n");
if (donType[4] == 0)
    printf("Fruit requests cannot be fulfilled.\n");

【讨论】:

  • 谢谢!正是我需要的。
  • 他实际上需要用else 语句替换else if 语句。你有它回到前面。
【解决方案3】:

在满足第一个 if 语句的 true 条件后,跳过 else 部分。删除 else 因为所有条件都是相互独立的。在您的情况下,作为第一个 if 语句将 s 评估为 true,其余语句会因为 else 而被跳过。

【讨论】:

    【解决方案4】:

    一旦满足条件,您的代码就会停止,这是完全自然的。在 C++ 中,当满足 if 条件时,它会跳过 else 语句。

    else if 基本上是一个可以重复使用的 else 语句。

    在您的情况下,要检查所有条件,您需要将 else if 语句替换为简单的 if 语句。

         if (donType[0] == 0) 
            printf("Protein requests cannot be fulfilled.\n");
         if (donType[1] == 0)
            printf("Dairy requests cannot be fulfilled.\n");
         if(donType[2] == 0)
            printf("Grain requests cannot be fulfilled.\n");
         if (donType[3] == 0)
            printf("Vegetable requests cannot be fulfilled.\n");
         if (donType[4] == 0)
            printf("Fruit requests cannot be fulfilled.\n");
    

    【讨论】:

    • 请注意,这个问题被标记为c 而不是c++
    • 不应该有 { } 在你拥有它的地方
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    相关资源
    最近更新 更多