This is my first regimen in C. I"d rather not form any kind of negative behavior currently. Is tbelow anypoint that looks favor bad practice, or somepoint simply looks wrong?

#incorporate #incorporate #encompass int main(void) srand(time(NULL)); int r = rand() % 10 + 1; int correct = 0; int guess; int respond to = 0; printf("Guess my number! "); carry out scanf("%d", &guess); if (guess == r) counter++; printf("You guessed appropriately in %d tries! Congratulations! ", counter); correct = 1; if (guess r) counter++; printf("Your guess is too high. Guess aobtain. "); while (correct == 0); rerevolve 0;
beginner c game number-guessing-game
Improve this question
edited Oct 5 "14 at 21:15


34.6k1313 gold badges128128 silver badges234234 bronze badges
asked Mar 26 "13 at 7:28

6311 gold badge11 silver badge33 bronze badges
Add a comment |

3 Answers 3

Active Oldest Votes
Here are some of the improvements i deserve to suggest:

relocate your respond to variable , from the inside the if statements , as raising the count is independent of the if problem.

You watching: Random number guessing game c++

Use srand(time(NULL)); , below the declarations , or else , your compiler might throw this warning , as soon as compiled making use of C90 typical.

warning: ISO C90 forbids mixed declarations and code <-pedantic>

So to ensure portability , stop statements in between declarations.

See more: Vbo'S; How They Work, And What Is Vbo In Minecraft, Vbos & Vsync

In the long run , more meaningful and also formal names , can be supplied rather of names choose r and also guess.

In my individual opinion , these 2 alters would be better:

Using a break; , when the correct number is guessed , deserve to get rid of the need for utilizing an additional variable correct.

See more: What Organelle Does Photosynthesis Take Place In, In What Cell Organelle Does Photosynthesis Occur

I would certainly prefer to use just a while() instead of dowhile();, if the routine logic permits it.

Here is the program , modified via the changes , i detailed above:

#include #include #include int main(void) int random_num = 0;int guessed_num = 0;int respond to = 0; srand(time(NULL));random_num = rand() % 10 + 1;printf("Guess my number! "); while(1) counter++; scanf("%d", &guessed_num); if (guessed_num == random_num) printf("You guessed effectively in %d tries! Congratulations! ", counter); break; if (guessed_num random_num) printf("Your guess is as well high. Guess aacquire. "); rerevolve 0;

Categories: Q&A