如何扫描所有 "else if" 条件 - C

How to scan through all "else if" conditions - C

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

        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 语句?请记住,我是这些东西的新手,所以我不需要任何复杂的答案。感谢您的帮助!

条件不互斥,所以只需删除 else 关键字,使它们都是独立的 if 语句。

您需要用 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++ 中,当满足 if 条件时,它会跳过 else 语句。

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

在您的情况下,要检查您需要用简单的 if 语句替换 else 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");

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