递归并打印结果

时间:2016-12-04 21:01:18

标签: 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

@EDIT

对于代码中的混乱感到抱歉。将变量名称从我的母语更改为英语。

1 个答案:

答案 0 :(得分:0)

fchance函数在打印任何内容之前找到ticket的值。我建议在printf语句之后移动chance = rand()...语句。                      - β