Is there any way I can change the range of the Rand function in the middle of the C code?

Asked

Viewed 331 times

-1

Hello, I was solving a college issue about a "game" in which you should think about a number and the machine should try to hit your number. I was able to do this work by creating a "formula" for him to find the value that the user thinks, but I would like the program to be a little more random, without the need for formulas. So the question is, is there a possibility of changing the Rand interval in the middle of the code? For each time he "kicks" a value, the interval decrease and he increases his chances of hitting the number.

#include<stdio.h>
#include<locale.h>
#include<string.h>
#include<stdlib.h>
#include <time.h>

int main(void){

setlocale(LC_ALL,"");
int t, in=0, f=100, cont=1, c;
char a[10];
printf("------------------------------Bem vindo(a) ao jogo de adivinhar um número!!!-----------------------\n\n");
printf("Funciona assim: você deve pensar em um número de 1 a 100 e eu vou tentar adivinhar seu número.\n");
printf("Eu vou dizer meu palpite e você responde se ele é maior ou menor que o número que você está pensando.\n");
printf("Você deve me dizer se eu acertei o número ou se o número que eu disse é maior ou menor que o número que você pensou.\n");
printf("Para vencer, eu devo acertar exatamente o número que você pensou.\n");
printf("Vamos começar? Pense num número para eu adivinhar.\n");
printf("\n\nQuando tiver terminado de pensar, digite 1 para continuar com o jogo: ");
scanf("%i", &c);
if(c==1){
while(1){
    srand( (unsigned)time(NULL) );
    t = in+ (rand () % f);
    if(cont==1){
        t=f/2;
    }else if(cont>1 && (f/2)>in){
        t=f/2;
    }printf("Seu número é %i, estou certo?\n", t);
    printf("Se acertei, digite (acertou), se não, digite se seu número é (maior) ou (menor) que meu número: ");
    fflush(stdin);
    gets(a);
    if(strcmp(a, "acertou")==0){
        printf("\n\n\nSou muito bom, não? Já acertei seu número!!\n\n\n");
        break;
    }else if(strcmp(a, "maior")==0){
        f = f + in;
        in = t;
        f = f-in;
        in++;
        printf("\n\nSeu número é maior do que o que eu disse? Ok, vou tentar novamente! \n\n\n");

    }else if(strcmp(a, "menor")==0){
        f = t - in;
        if(f>1){
            f--;
        }printf("\n\nSeu número é menor do que o que eu disse? Ok, vou tentar novamente! \n\n\n");

    }
    cont++;
}
}else{
    printf("\n\nDígito inválido! Da próxima vez digite 1 para continuar com o jogo!\n\n");
}
return 0;
}
  • First, define "a little more random, no need for formulas". If you want the interval to be random just have no interval The interval is precisely to tr a limit. If you just want to lower the limit is decreasing the randomness, if you want to increase, just increase the interval and that’s it. At the extreme of the increase is to have no interval. If you want to insist on this, do the in and the f be random too. It’s silly. Other than that ,I just advise organizing the code a little bit, defining better names for things.

  • Thanks for the answer first, and I’m sorry for the messy variables. In this case the "least random" would be to kick a literally random number between 0 and 100. In the formula I made it always starts from 50, if I say that the value is lower it goes following a formula, you know? I would like to know if there are ways to leave this less "robotic" and more at the same chance. Of course, it wouldn’t be purely a chance since I’m narrowing it down, but I think I’ve made my point. Anyway, it’s a question of just curiosity. Is there any way?

2 answers

1

The code has some problems. The main thing is to use the operator == to compare strings. In C a string is just a string and needs a proper function to compare all of them and return whether it is larger, smaller or equal. This function is the strncmp(). In fact any language needs to do so, but some hide it in the operator, but this is another subject and I will not go into details.

Another problem of this code is trying to return a local variable. This is not possible since the content in stack may not be available anymore. You have compiler you let do, which is bad since there is great possibility of memory corruption. In the compiler I used, neither compiles.

So the solution is to pass one buffer for the function with pre-allocated memory. Then who needs the text allocates as you like and releases if necessary. It is only necessary to use the malloc(). In some cases it is possible to use a array in place of the pointer and dynamic allocation.

I could even do the allocation within the function and return this pointer, but this is usually bad because the programmer might forget that he needs to do the release. It gets an asymmetrical thing, the function allocates and another function takes care of the release.

I made him return his own buffer so that the function can be used as expression as well, but if this were never necessary (unlikely in real code), it could return nothing, since the passage of the buffer is made by a pointer, therefore it is a reference to the actual object.

Note that I have simplified the function. This function is not secure, nothing guarantees that enough memory has been allocated to fit the substring. At the moment nothing prevents the end from being less than the beginning, which would be a mistake. It would be nice to improve it to treat these things.

I understand this is an exercise, but the use of memcpy() is more appropriate in this situation than tying up on one’s own.

There was another problem adding up the end and beginning of the string. Now there’s no more, but if this was still in the code, it would be wrong, it’s the opposite, it should be a difference.

Avoid using unnecessarily flagged type.

There are small code organizations that I’ve made too.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *substring(char *str, char *buf, int start, int end) {
    for (int i = start; i < end; i++) buf[i] = str[i];
    return buf;
}

int main() {
    char *texto = malloc(6);
    if (strncmp(substring("Hello World", texto, 0, 5), "Hello", 5) == 0) printf("yep");
    free(texto);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

In C++ everything would be different because it has a type string "native".

0


Changes the srand() out of the cycle.

Change the statement that has the rand() to consider minimum and maximum values, for example using, minval and maxval to calculate the number intermedio (use rand() to find the number the user selected is not efficient)

int minval = 1;
int maxval = 100;

    // dentro do ciclo
    t = (maxval - minval + 1) / 2 + minval;

Every time you get an answer "menor" or "maior" changes one of the values

    if (strcmp(a, "maior") == 0) {
        minval = t + 1;
    }
    if (strcmp(a, "menor") == 0) {
        maxval = t - 1;
    }

For example to guess the number 61 the sequence of variables would be like this:

                                                         |   novos
minval | maxval |  t | calculo                   | res   | min | max
-------+--------+----+---------------------------+-------+-----+-----
    1  |   100  | 51 | (100 - 1 + 1) / 2 + 1     | maior |  52 | 100
   52  |   100  | 76 | (100 - 52 + 1) / 2 + 52   | menor |  52 |  75
   52  |    75  | 64 | (75 - 52 + 1) / 2 + 52    | menor |  52 |  63
   52  |    63  | 58 | (63 - 52 + 1) / 2 + 52    | maior |  59 |  63
   59  |    63  | 61 | (63 - 59 + 1) / 2 + 59    | acertou 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.