我試圖讓我的程式在回答三遍后列印“停止回答錯誤的怪胎”,但我似乎無法讓我的while回圈來實作這一點,如果有人可以提供幫助,我是一個超級初學者,所以任何提示將不勝感激。
我試圖x每次都增加計數器是否,然后如果你再次回答沒有錯,while回圈結束并出現另一條訊息。
非常感謝。
char n[20];
int x = 0;
do {
printf("Are you cool yes/no ? ");
scanf("s", n);
if (strcmp(n, "yes") == 0) {
printf("%s is the correct answer, i can only be friends with cool people\n", n);
break;
} else
x , printf("%s is the wrong answer, i only like cool people sorry!\n", n);
} while (!strcmp(n, "yes") && x < 3);
printf("stop answering wrong freak!\n");
break;
uj5u.com熱心網友回復:
不要使用do/while回圈,使用for ever回圈并適當地中斷:
for (int x = 0;;) {
char n[20];
printf("Are you cool yes/no ? ");
if (scanf("s", n) != 1) {
printf("end of file already? I don't like leavers\n");
break;
}
if (strcmp(n, "yes") == 0) {
printf("%s is the correct answer, I can only be friends with cool people\n", n);
break;
}
printf("%s is the wrong answer, I only like cool people sorry!\n", n);
if ( x == 3) {
printf("I am not listening to you anymore!\n");
break;
}
}
uj5u.com熱心網友回復:
您的代碼具有大部分邏輯正確,但只需要進行一些調整即可完成您的要求。
就像提到的 Weather Vane 一樣,沒有必要在 while 回圈的每次迭代中都使用 strcmp 進行測驗,您已經在 if 陳述句中這樣做了。您只需要檢查以確保 x 仍在您決定的限制范圍內,3。
最后,當您的程式完成時,您需要通過添加這樣的 if 陳述句來確保非酷人的 printf 陳述句不會列印給酷人:
if(x == 3)
{
printf("stop answering wrong freak!\n");
}
所以你的完整代碼是這樣的:
#include <stdio.h>
int main()
{
char n[20];
int x = 0;
do {
printf("Are you cool yes/no ? ");
scanf("s", n);
if (strcmp(n, "yes") == 0)
{
printf("%s is the correct answer, i can only be friends with cool people\n", n);
break;
}
else
{
x , printf("%s is the wrong answer, i only like cool people sorry!\n", n);
}
} while (x < 3);
if(x == 3)
{
printf("stop answering wrong freak!\n");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/487795.html
標籤:C
上一篇:靜態修飾符如何在C中作業?
