# 小專題1 電子雞自己猜數字 姓名:李志鴻 年級:資訊二乙 學號:D1014210 **以下是我的猜數字程式碼。** ``` #include <stdio.h> #include <stdio.h> #include <stdlib.h>#include <stdlib.h> int main() { int random = 0, count = 0, num; //計算隨機號碼 random = rand() % 1000; //隨機號碼的loop while (1) { //遞增count count += 1; //輸入號碼 printf("\n請輸入一個號碼(0 to 1000): "); scanf("%d", &num); //比較random和num if (num == random) { printf("恭喜你!你在第%d次猜對了!\n", count); break; } else if (num < random) { printf("號碼不對哦。你的號碼還比較小哦。請再輸入。。。。\n"); } else if (num > random) { printf("號碼不對哦。你的號碼還比較大哦。請再輸入。。。。\n"); } //限制次數 if (count == 10) { printf("\n\n你的輸入次數已到!下次再接再厲!"); break; } } return 0; } ``` 首先,我開了三個宣告。 * random是讓玩家輸入的。 * count是用來計算次數。 * num是隨機的,就是我們要猜的號碼。 ``` int random = 0, count = 0, num; ``` 第二,我對random進行了運算。 * % 1000 是為了取餘數。 ``` random = rand() % 1000; ``` 第三,迴圈。 ``` while (1) { count += 1; printf("\n請輸入一個號碼(0 to 1000): "); scanf("%d", &num); if (num == random) { printf("恭喜你!你在第%d次猜對了!\n", count); break; } else if (num < random) { printf("號碼不對哦。你的號碼還比較小哦。請再輸入。。。。\n"); } else if (num > random) { printf("號碼不對哦。你的號碼還比較大哦。請再輸入。。。。\n"); } if (count == 10) { printf("\n\n你的輸入次數已到!下次再接再厲!"); break; } ``` 當while執行時,會先計算count。 ``` count += 1; ``` 這時就開始讓玩家隨機輸入號碼。 ``` printf("\n請輸入一個號碼(0 to 1000): "); scanf("%d", &num); ``` 輸入結束之後就是驗證號碼了。 ``` if (num == random) { printf("恭喜你!你在第%d次猜對了!\n", count); break; } else if (num < random) { printf("號碼不對哦。你的號碼還比較小哦。請再輸入。。。。\n"); } else if (num > random) { printf("號碼不對哦。你的號碼還比較大哦。請再輸入。。。。\n"); } ``` 驗證結束後,我在程式碼裡設定了次數,count就是次數,不能超過10次。 ``` if (count == 10) { printf("\n\n你的輸入次數已到!下次再接再厲!"); break; } ``` **成果如下:**  # 謝謝!
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up