dimanche 4 décembre 2016

Recursion and printing the result

my task is to draw a random number as a ticket in a lottery. Then I need to guess what number is it. This operation of guessing needs to be done 100 times. I don't know if my program works good because every time I print the chances on the screen it gives me the proper answer in each step. I have steps variable globally declared, so probably that's why it is always the same. But what about chance?

#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;
}

The example of output:

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

Sorry for the mess in the code. Changed variable names from my native language to english.




Aucun commentaire:

Enregistrer un commentaire