我是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;
}
有人可以告诉我如何改进或出错的地方吗?
答案 0 :(得分:3)
您需要将所有代码放在do
和while
语句之间。
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 loop
和do while loop
- 我首先要重构这个概念。
答案 3 :(得分:0)
您的问题的逻辑是:
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);