www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/12/07/01:42:34

Message-ID: <384D8454.D2E3CB88@cal2.vsnl.net.in>
Date: Tue, 07 Dec 1999 12:04:05 -1000
From: "Dr. Keya Chaudhuri" <keya AT cal2 DOT vsnl DOT net DOT in>
X-Mailer: Mozilla 4.01 [en] (Win95; I)
MIME-Version: 1.0
To: djgpp AT delorie DOT com
Subject: Re: Pls help!!
X-Priority: 3 (Normal)
References: <82gnhb$dm2$1 AT imsp026 DOT netvigator DOT com>
Reply-To: djgpp AT delorie DOT com

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019