C語言循環練習
練習題5_9:設計一個游戲,“開口中”,首先,在1到100內選一個數字為底數,然後,用戶要輪流輸入1到100以內的數字,每輸入一次,如果不是底數,就把范圍縮小到嘉賓輸入的那個數,直到輸入中底數為止。
最佳回答:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int luckyNumber, picked, l = 1, r = 100;
srand(time(NULL));
luckyNumber = rand() % 100 + 1;
while (1) {
printf("Enter a number between %d and %d :>", l, r);
scanf("%d", &picked);
if (picked < l || picked > r) {
printf("The number shall be within the range of %d and %d!\n", l,
r);
continue;
} else if (picked < luckyNumber)
l = picked;
else if (picked > luckyNumber)
r = picked;
else
break;
}
printf("You got me...\nThe number is &d.\n", luckyNumber);
return 0;
}