First, please post your code here on the forum, in code tags, and make sure it is neatly indented:
Code:
#include<stdio.h>
#include<stdlib.h>
int display_question();
static int result;
int main()
{
char a;
int b,c,d,e,f;
srand(time(NULL));
printf("WELCOME GAME!!!\n");
a='c';
display_question();
printf("Now,please enter your answer");
scanf("%d",&f);
if (f != result)
{
printf("c or e");
scanf(" %c",&a);
if (a=='e')
return 1;
}
while (a=='c')
{
display_question();
printf("Now,please enter your answer\n");
scanf(" %d",&f);
printf("RESULT IS ----> %d\n",f);
if (f==result)
{
printf("TRUE..press 'c' to continue or 'e' to end\n");
scanf(" %c",&a);
if (a=='e')
{
printf("GOOD BYE!!!\n");
return 1;
}
}
if (f != result)
{
printf("Sorry,WRONG ANSWER..press 'c' to continue or 'e' to end\n");
scanf(" %c",&a);
if ( a == 'e')
{
printf("GOOD BYE!\n");
return 1;
}
}
}
return 0;
}
int display_question()
{
int x,y,z;
x = 1+rand() % 100;
y = 1+rand() % 100;
z =1+ rand() % 4; // produce 1,2,3,4...
switch(z)
{
case 1:
{
printf("What is the result of ---> # %d * %d ? #\n",x,y);
result = x*y;
break;
}
case 2:
{
printf("What is the result of ---> # %d / %d ? #\n",x,y);
result = x/y;
break;
}
case 3:
{
printf("What is the result of ---> # %d + %d ? #\n",x,y);
result = x+y;
break;
}
case 4:
{
printf("What is the result of ---> # %d - %d ? #\n",x,y);
result = x-y;
break;
}
}
return 0;
}
"scanf()" tries to read the type you tell it to expect ... but if you enter a type it doesn't expect (such as entering a character when an integer is expected), it will fail to read the input, and the input will remain in the buffer. This could mess up further input reads, as it might continue to try to read input that is not expected.
Fortunately, the "scanf()" function returns the number of item successfully read. So you can use this as a rudimentary form of input validation (though more robust input validation is strongly recommended).
For an example, run the following program:
Code:
#include <stdio.h>
int main(void)
{
int x;
int result;
printf("Enter an integer:\n");
result = scanf("%d",&x);
if(result == 1)
printf("You entered the integer: %d\n",x);
else
printf("You did not enter an integer\n");
return 0;
}
The first time, enter a number (e.g. 34).
The second time, enter a character (e.g. the letter 'v').
Compare the output of each run, and notice how the return value of "scanf()" is checked.