4

我是 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

4 回答 4

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
于 2013-08-02T02:11:36.067 回答
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();
}
于 2013-08-02T02:24:39.457 回答
0
do {
    // stuff
}
while {
    // more stuff
}

将 2 个概念混合在一起:thewhile loop和 the do while loop- 我将从重构该部分开始。

于 2013-08-02T02:10:46.430 回答
0

您的问题的逻辑是:

  1. 在输入不是 -1 时继续运行。如果输入为 -1,则中断/退出执行并显示输出。
    1. 输入等级。
    2. 如果等级小于或等于 100 或大于或等于 0,则执行通过/失败检查:
      1. 如果等级大于或等于 50,则该人已通过。增加通过次数。
      2. 如果分数低于 50,则该人不及格。增加失败的考试次数。

jh314的布局逻辑是正确的,但没有修复执行逻辑:

  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);
于 2013-08-02T02:20:59.093 回答