Hi, I would like to ask, is there any method for us to determine the code for the following output.
√729 =
? n
Question skipped!
15² =
? 225
Yes, you are right!
√256 =
? w
Wrong input! Please re-enter the answer.
? 25
Sorry, you are wrong! |
This is a mathematics quiz program. The program will show a question for the user and when the user enter the answer, the answer will be stored in string. I got two method of myself in writing those codes. However, the result output is not as what the formatted output shown. Firstly, I treat all the variables as integer to make comparison. When it comes to 123e, it will assume the ans as 123 when I use atoi(). In another method, I convert the calculated answer into string by using itoa(), when I do string comparison, several error appears. As example, when user press n, instead of skipping the question, the program shows wrong answer for user. And when user enter without alphabet in the answer, such as 35 which is not the answer for that question, it will say that it is wrong input which will ask user enter again. During this, the program should instead show wrong answer rather than prompt for answer again. Any idea on dealing with this condition?
I attached my code here for reference. I would like to hear any suggestion and comments from all of you. Thanks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
using namespace std;
int main ()
{
int num1, num2;
char ans[5],ans_cal[5];
srand((unsigned) time(0));
num1 = rand() %30 + 1;
cout << num1 << (char)253 " = " << endl << "? ";
cin >> ans;
fflush (stdin);
num3 = pow(num1,2);
_itoa_s(num3,ans_cal,5,10);
while (strcmp(ans,ans_cal) != 0 && !atoi(ans)!=atoi(ans_cal)){
cout << "Invalid input, please enter again: ";
cin >> ans;
fflush(stdin);
}
if (toupper(ans[0])=='N' && strlen(ans)==1){
cout << "Question skipped" << endl;
}
else if (strcmp(ans,ans_cal)==0)
{
cout << "Correct answer" << endl;
}
else if (strcmp(ans,ans_cal)!=0 && atoi(ans)!=atoi(ans_cal)){
cout << "Wrong answer" << endl;
}
return 0;
}
|
This is just a portion of my code, which did the validation for the question about square only.