Mail Archives: djgpp/1999/12/07/01:42:34
Jason Yip wrote:
>
> I wrote the following program.. I want the right answer shows "Very Good",
> the wrong answer shows "No" and input again.. but why my progam like this:
> 1st answer always correct.. the 2nd answer always wrong...
> How can I solve it? Thx a lot!!
>
> #include <stdio.h>
> #include <stdlib.h>
> #include <time.h>
> main ()
> {
> int ans,h;
> printf("Enter -1 to end\n");
> do{
> srand(time(NULL));
> printf("How much is %d times %d? ",1+(rand()%9),1+(rand()%9));
> ans=(1+(rand()%9))*(1+(rand()%9)); *******Note this line
> scanf("%d",&h);
> if (ans == h)
> printf("Very Good!\n");
> else
> if (ans != h){
> do{
> printf("No. Please try again.\n");
> printf("? \n");
> scanf("%d",&h);} while (ans != h);
> }} while (ans != -1);
> if (ans == -1)
> printf("That's all for now. Bye.");
> return 0;
> }
In the marked line,what you did was ,generated two more new random
numbers (by further calls to rand()) and took their sum.These are
obviously different from the previous random numbers.
To get the correct result,try this:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main ()
{
int ans,h;
int a,b;
printf("Enter -1 to end\n");
do{
srand(time(NULL));
a=1+(rand()%9);
b=1+(rand()%9);
printf("How much is %d times %d? ",a,b);
ans=a*b;
scanf("%d",&h);
if (ans == h)
printf("Very Good!\n");
else
if (ans != h){
do{
printf("No. Please try again.\n");
printf("? \n");
scanf("%d",&h);} while (ans != h);
}} while (ans != -1);
if (ans == -1)
printf("That's all for now. Bye.");
return 0;
}
- Raw text -