C计算在输入负数时计算通过或失败等级的数量并退出的程序

时间:2013-08-02 02:07:14

标签: c loops do-while

我是C编程的新手,我们仍然在开始循环。对于我们今天的练习,我们的任务是创建一个do-while程序,计算有多少通过和失败等级但是当输入负数时循环中断。此外,跳过超过100的数字。这是我的计划:

#include<stdio.h>
#include<conio.h>

int main()
{
int grade, pass, fail;

pass = 0;
fail = 0;

do {
    printf("Enter grade:\n");
    scanf("%d", &grade);
    printf("Enter -1 to end loop");
}

while(grade == -1){
    if(grade < 100){
        if(grade >= 50){
        pass = pass + 1;
        }
        else if {
        fail = fail + 1;
        }
    }
    break;
}
printf("Pass: %d", pass);
printf("Fail: %d", fail);

getch ();
return 0;
}

有人可以告诉我如何改进或出错的地方吗?

4 个答案:

答案 0 :(得分:3)

您需要将所有代码放在dowhile语句之间。

do {
     printf("Enter -1 to end loop");
     printf("Enter grade:\n");
     scanf("%d", &grade);         

     if(grade <= 100 && grade >= 0) {
          if(grade >= 50){
               pass = pass + 1;
          }
          else {
               fail = fail + 1;
          }
     }

} while(grade >= 0);

do-while循环的一般结构是:

do {
   // all of the code in the loop goes here

} while (condition);
// <-- everything from here onwards is outside the loop

答案 1 :(得分:2)

#include <stdio.h>
#include <conio.h>

int main()
{
    int grade, pass, fail;

    pass = 0;
    fail = 0;

    do {
        printf("\nEnter grade:\n");
        scanf("%d", &grade);
        printf("Enter -1 to end loop");

        if (grade < 100 && grade >= 50)
            pass = pass + 1;
        else 
            fail = fail + 1;
        printf("\nPass: %d", pass);
        printf("\nFail: %d", fail);
    }
    while (grade >= 0);

    getch();
}

答案 2 :(得分:0)

do {
    // stuff
}
while {
    // more stuff
}

将2个概念混合在一起:while loopdo while loop - 我首先要重构这个概念。

答案 3 :(得分:0)

您的问题的逻辑是:

  1. 输入不是-1时继续运行。如果输入为-1,则中断/退出执行并显示输出。
    1. 输入成绩。
    2. 如果等级小于或等于100或大于或等于0,则执行通过/失败检查:
      1. 如果等级大于或等于50,则该人已通过。增加通行证数量。
      2. 如果成绩低于50,那个人就失败了。增加失败考试的次数。
  2. jh314's layout logic是正确的,但不修复执行逻辑:

      int grade, pass, fail;
    
      pass = 0;
      fail = 0;
    
      do {
         printf("Enter -1 to end loop");
         printf("Enter grade:\n");
         scanf("%d", &grade);
    
         //you want grades that are both less than or equal to 100
         //and greater than or equal to 0
         if(grade <= 100 && grade >= 0){
              if(grade >= 50){
                   pass = pass + 1;
              }
              //if the grades are less than 50, that person has failed.
              else {
                   fail = fail + 1;
              }
         }
    
      } while(grade != -1);
    
      printf("Pass: %d", pass);
      printf("Fail: %d", fail);