c - 递归并打印结果

标签 c recursion random

我的任务是抽取一个随机数作为彩票。然后我需要猜测它是什么数字。这个猜测的操作需要进行100次。我不知道我的程序是否运行良好,因为每次我在屏幕上打印机会时,它都会在每一步中给我正确的答案。我有全局声明的步骤变量,所以可能这就是为什么它总是相同的。但是机会呢?

#include<stdio.h>
#include<time.h>

int fchance(int min, int max, int ticket);
int steps = 0;
int main(void) {
    int ticket, chance;
    int i;
    int stepsInTry = 0;
    int stepsAverage;
    srand(time(NULL));
    // rand() % (max - min) + min;
    for (i = 0; i < 100; i++) {
        ticket = rand() % 100 + 1;
        printf("Your ticket: %d ", ticket);
        steps = 1;
        chance = rand() % 100 + 1;
        printf("\nChance: %d", chance);
        while (ticket != chance) {
            if (chance < ticket) {
                chance = ftraf(chance, 100, ticket);
                printf("\nChance: %d, step: %d", chance, steps);
            }
            if (chance > ticket) {
                chance = ftraf(1, chance, ticket);
                printf("\nChance: %d, step: %d", chance, steps);
            }
        }
        printf("\nOperation nr: %d - number of steps: %d \n", i+1, steps);
        stepsInTry += steps;
        system("PAUSE");
    }

    stepsAverage = stepsInTry / 100;
    printf("\n\nAverage of steps: %d ", stepsAverage);
    system("PAUSE");
    return 0;
}

int fchance(int min, int max, int ticket) {
    steps++;
    int chance;
    chance = rand() % (max - min) + min;

    if (chance < ticket) {
        chance = fchance(chance, 100, ticket);
        printf("\nChance: %d, step: %d", chance, steps);
    }
    if (chance > ticket) {
        chance = fchance(1, chance, ticket);
        printf("\nChance: %d, step: %d", chance, steps);
    }
    return chance;
}

输出示例:

Your ticket: 65
Chance: 38
Chance: 65, step: 11 
Chance: 65, step: 11 
Chance: 65, step: 11 
Chance: 65, step: 11 
Chance: 65, step: 11 
Chance: 65, step: 11 
Chance: 65, step: 11 
Chance: 65, step: 11 
Chance: 65, step: 11 
Chance: 65, step: 11 
Operation nr: - numbers of steps: 11

@编辑

对于代码中的困惑,我们深表歉意。将变量名称从我的母语更改为英语。

最佳答案

您的 fchance 函数在打印任何内容之前查找 ticket 的值。我建议将 printf 语句移至 chance = rand()... 语句之后。 – 测试版

关于c - 递归并打印结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40963606/

相关文章:

c# - 具有 10 个元素的随机 boolean 数组,其中 10 个元素中有 3 个为真

c - 二叉搜索树,常量NULL返回

c - 在 c 中的流式套接字上读取消息

c - 我的二进制搜索功能无法正常工作

python - 在Python中递归打印对象的所有属性、列表、字典等

python-3.x - odoo 11/Python 3 : How to find expiry date of subscription if some weekdays are excluded

C警告冲突类型

c - 使用 malloc 时 C 中的奇怪段错误

python - 如何在Python中使用random.sample()后获取剩余的样本?

java - 如何选择距引用点一定距离的随机点