简体   繁体   English

if-else语句

[英]if-else statement

My codes allows the user to enter in a score from 1 to 100, which will either tell them that the score is "Good", "OK", "Moron", or "Invalid". 我的代码允许用户输入1到100的分数,这将告诉他们分数是“好”,“好”,“莫伦”或“无效”。

But, when I compile these codes. 但是,当我编译这些代码时。 The output has invalid in it too with the correct statement if it is more than 54. 如果输出超过54,则输出也是无效的。

For example : 例如 :

  • if I enter in 55 it will say "OK" AND "Invalid". 如果我输入55,它会说“OK”和“Invalid”。
  • if I enter in 54 it will just say "Moron". 如果我进入54,它只会说“莫伦”。

Here are my codes: 这是我的代码:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>

void main()   
{
    int score;
    printf("Enter a Score");
    scanf("%d", &score);
    if (score >=80 && score <= 100){
        printf("Good\n",);
    }
     if (score >=55 && score <=79){
        printf("OK\n",);
    }
     if (score >=1 && score <=54){
        printf("Moron\n",);
    }
    else{
        printf("Invalid\n");
    }    
    system("pause");
}

It is happening because instead of using one control flow you use multiple (thus if condition is met before the last if control flow ( score >= 55 through score <= 100 ), else code from the last one is also executed). 它正在发生,因为,而不是使用一个控制流使用多个(因此,如果条件之前的最后一个满足if控制流程( score >= 55通过score <= 100 ), else也执行从最后一个代码)。 You can use else if branches: else if分支你可以使用else if

if (score >= 80 && score <= 100){
   printf("Good\n",);
} else if (score >= 55 && score <= 79){
   printf("OK\n",);
} else if (score >= 1 && score <= 54){
   printf("Moron\n",);
} else {
   printf("Invalid\n");
}

You can also use nested if / else statements, but the solution above seems less cumbersome. 您也可以使用嵌套的if / else语句,但上面的解决方案似乎不那么麻烦。

Each if statement is a standalone conditional statement. 每个if语句都是一个独立的条件语句。 Your example has three groups of conditional statements: 您的示例有三组条件语句:

  1. if (score >=80 && score <= 100)
  2. if (score >=55 && score <=79)
  3. if (score >=1 && score <=54) { ... } else { ... }

So if score has the value 55 , it will match against #2 above and the else of #3. 因此,如果score的值为55 ,则它将与上面的#2和#3的else值匹配。

One solution here would be to combine the above statements into one group. 这里的一个解决方案是将上述语句组合成一个组。 You can do this with else if . 您可以使用else if来执行此操作。

eg 例如

if (*expr*) {
    ...
} else if (*expr*) {
    ...
} else if (*expr*) {
    ...
} else {
    ...
}

You have 2 if-else statements and both get executed. 你有2个if-else语句并且都被执行了。 So you will do "something" for both of them. 所以你会为他们两个做“某事”。 Walk through your code with score=55 and you'll find the problem. score=55浏览代码,您就会发现问题所在。

2 solutions: 2解决方案:

  1. Make the if s "standalone" (so only one will pass) 使if “独立”(因此只有一个会通过)
  2. Add some else s to ensure only one of your branches executes. 添加else一些以确保只执行一个分支。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM