There are several problems with this code. First, I wouldn’t use a function for this, it doesn’t look like it needs it, there’s no clear reason to use it if there’s no reason not to. If it is to use function do in something that encapsulates a specific logic. Of course it can, but it seems an artificial use. Almost always it will be used only once it doesn’t make much sense to create the function, unless something is too big or has a separate clear logic. In case I think logic is weird and at least I tried to make it more correct thinking that hit the random is a logic and try another number is another logic, done so until the function makes some sense.
I separated the seed startup because in the way it is doing is unnecessary is almost wrong, in this case it even works because it initializes over time, but seed initializes once per application. and the comment used gives an indication of the wrong of what the function does, it does not generate any number, who generates is the rand()
.
I took the part that prints the drawn number because it doesn’t make sense for a guessing game to show the number to be guessed.
I changed the text to make it clearer how to close the game. The text of the hit still seems odd because the person will hit, or she can’t even leave the game, but anyway, this is something that should be improved.
If the function returns nothing then its type should be void()
.
I initialized tent
because you might never even get in the loop because of this.
And of course I eliminated code repetition in both functions leaving the logic of repetition only in one, correctly.
I eliminated unnecessary things and wrote the code in a more organized way. Other things can be improved on this.
As an exercise give better names to the variables, especially without abbreviating, leave readable, do not be lazy to dictate the whole name. If you want to type less stop by things that are not needed in the code and will type less while maintaining readability.
#include <stdio.h>
#include <stdlib.h>
#include<time.h>
void aleatorio(int niv) {
int aleat = (rand() % niv) + 1;
int tent = -1;
while (aleat != tent) {
printf("Digite o numero secreto");
scanf("%d", &tent);
}
printf("parabéns voce acertou!!\n");
}
int main() {
srand((unsigned)time(NULL));
int niv, res = -1;
printf("Digite o numero limite: ");
scanf("%d", &niv);
while (res != 0) {
aleatorio(niv);
printf("Deseja jogar novamente? (0 - Não 1 - Sim)");
scanf("%d", &res);
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Thank you,understood the explanation,about the secret number is printando was to facilitate the tests. Thank you again.
– Lolzeiro