题目

猜数字:程序随机数,用户多次猜测

思路

本题「猜数字」:程序随机生成秘密数,用户多次猜测直到猜中。

srand 初始化随机种子,rand()%N+1 生成范围;循环读入猜测,比较输出偏大/偏小/正确,猜中后结束。

解题分析

固定种子的 rand 便于对拍。线性猜可以二分:每次猜中间值,根据 high/low 折半区间,比随机猜次数更少(可写进其它写法)。

完整程序

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    srand(42);
    int secret = rand() % 100 + 1;
    int guess, tries = 0;
    while (scanf("%d", &guess) == 1) {
        tries++;
        if (guess > secret) {
            printf("high\n");
        } else if (guess < secret) {
            printf("low\n");
        } else {
            printf("ok %d\n", tries);
            break;
        }
    }
    return 0;
}

运行示例

输入:

50
90
70
(�?secret 而定)

输出:

high/low 提示�?ok

其它写法

下面每种写法都是完整程序,输入输出格式与正文一致,便于对照。

二分猜数

固定种子 secret 与正文相同,用二分减少猜测次数。

程序:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    srand(42);
    int secret = rand() % 100 + 1;
    int lo = 1, hi = 100, guess, tries = 0;
    while (scanf("%d", &guess) == 1) {
        tries++;
        if (guess > secret) {
            printf("high\n");
            hi = guess - 1;
        } else if (guess < secret) {
            printf("low\n");
            lo = guess + 1;
        } else {
            printf("ok %d\n", tries);
            break;
        }
        if (lo > hi) {
            break;
        }
    }
    return 0;
}

运行示例

输入:

50
75
62
68
66
65

输出:

high
high
low
high
low
ok 6