[英]How to terminate the program?
一旦用戶將 1 輸入到決策部分,我就試圖終止程序,但即使在用戶輸入 1 之后它仍然繼續要求輸入。我在代碼中做錯了什么或遺漏了什么? 請幫忙,我似乎不明白它有什么問題。
#include <stdio.h>
int main()
{
int H, N, mark, s, n, last;
/*Student Marks Input, Grade Output/Loop*/
do
{
printf("Please enter your marks:");
scanf("%i", &mark);
if(mark>100)
{
printf("Invalid Input\n");
printf("Re-enter your marks:");
scanf("%i",&mark);
}
if(mark>=80)
{ H++;
printf("You got a H\n");
}
else
if(mark>=70)
{
printf("You got a D\n");
}
else
if(mark>=60)
{
printf("You got a C\n");
}
else
if(mark>=50)
{
printf("You got a P\n");
}
else
if(mark<=49)
{
N++;
printf("You got an N\n");
}
/*Decisions*/
printf("Are you the last student?(Y=1/N=0):");
scanf("%i", &last);
if(last==0)
{
n++;
}
else if (last==1)
{
s++;
}
}
while(s>0);
/*Results*/
if(H>N)
printf("Good Results");
else
printf("Bad Results");
return 0;
}
首先,您的代碼中有未定義的行為,就像您對未初始化的變量進行操作一樣。
未初始化的局部變量,例如s
,具有不確定的值,並且執行例如s++
將導致未定義的行為。 變量s
並不是您未初始化然后對其執行操作的唯一變量。
然后當您初始化s
,請記住循環會繼續迭代while (s > 0)
,因此如果您將s
初始化為零,則執行s++
,這意味着s
將大於零並且循環繼續。
您應該將(我推薦) s
初始化為零,然后循環while (s == 0)
。
或者,你知道,只是break
循環了:
if (last == 1)
break;
// No else, no special loop condition needed, loop can be infinite
您的縮進使 do ... while 循環看起來像是一個無限循環。 在從 do ... while 中刪除 while 的分數之后,您還有一個額外的右括號。 這實際上使它成為一個無限循環。
#include <stdio.h>
int main()
{
int H, N, mark, s, n=0, last;
/*Student Marks Input, Grade Output/Loop*/
do
{
// processing
if(last==0)
{
n++;
}
else if (last==1)
{
s++;
}
} // This converts the do ... while into an infinite loop
while(s>0); // This is an invalid while since it never gets here
一開始把這個改成while
#include <stdio.h>
int main()
{
int H, N, mark, last;
int s = 0;
int mark = 0;
/*Student Marks Input, Grade Output/Loop*/
while (s < 1) // First loop runs sinc s is initialized to 0.
{
// Get the entry for the next pass through the loop.
printf("Please enter your marks:");
scanf("%d", &mark);
// Perform your processing
/*Decisions*/
printf("Are you the last student?(Y=1/N=0):");
scanf("%i", &last);
if(last==0)
{
n++;
}
else if (last==1)
{
s++;
}
// This is the end of the while loop
}
/*Results*/
if(H>N)
printf("Good Results");
else
printf("Bad Results");
return 0;
}
現在,當最后一個學生進入標記時,它將按照您的預期退出循環
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.