![](/img/trans.png)
[英]Cygwin1.dll 'not found' when running a program written in C. How can I make Windows find it?
[英]“Guess the Number between 1-1000 game” in C. How can it be made to replay without manually running the program again?
所以我有我的第一個 C 程序,您可以在其中猜測 1 到 1000 之間的數字。它玩得很好,但是當我按 Y 或 N 讓用戶在獲勝后重玩游戲時,它只是結束了程序。 我想 n 殺死程序, y 重新啟動它。 我該如何做到這一點? 這是程序。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int random_num = 0;
int guessed_num = 0;
int counter = 0;
char selection = 'y';
srand(time(NULL));
random_num = rand() % 1000 + 1;
printf("I have a number between 1 and 1000, can you guess my number??? ");
while (selection == 'y')
{
counter++;
scanf_s("%d", &guessed_num);
if (guessed_num == random_num)
{
printf("You guessed correctly in %d tries! Congratulations! Guess again? (y or n)\n", counter);
scanf_s("%d", &selection);
break;
}
if (guessed_num < random_num)
printf("Your guess is too low. Guess again. ");
if (guessed_num > random_num)
printf("Your guess is too high. Guess again. ");
}
return 0;
}
您的程序正在這里等待用戶輸入:
if (guessed_num == random_num)
{
printf("You guessed correctly in %d tries! Congratulations! Guess again? (y or n)\n", counter);
scanf_s("%d", &selection);
break;
}
即使用戶選擇“是”或“否”,根據您的邏輯,您也可以使用“中斷”語句。 這打破了你的無限游戲循環,即使在輸入“y”之后你也會出來。 因此,請使用上一個答案中所述的解決方案。 希望這可以消除您的疑問
將你的“玩一次游戲”邏輯放在一個更大的循環中,玩完游戲后,會問“你想再玩一次嗎?”。
char play_again = 'y';
while ( play_again == 'y' ) {
...
printf("do you want to play again?");
scanf_s("%c", &play_again);
}
在您詢問用戶是否想再次播放之后,您無條件地調用break
。 無論他們選擇什么, break
都會跳出while
循環,退出你的程序。 干脆擺脫break
。 您也可以更改為else if
... else
條件,因為每個檢查都是互斥的; 例如,如果我們知道==
是真的,那么檢查<
或>
是沒有意義的。
if (guessed_num == random_num)
{
printf("You guessed correctly in %d tries! Congratulations! Guess again? (y or n)\n", counter);
scanf_s("%d", &selection);
}
else if (guessed_num < random_num)
{
printf("Your guess is too low. Guess again. ");
}
else
{
printf("Your guess is too high. Guess again. ");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.