-
Help with Pseudo numbers
i have written a model program . though my actual program contains another set of questions(the questions i have used here are real easy.)
i have made use of srand and rand funtions
here is my code
Code:
#include<iostream>
#include<conio.h>
#include <cstdlib>
#include <ctime>
using namespace std;
main()
{
srand((unsigned)time(0));
int question,score=0;
int option1,option2,option3,option4;
for(int a=1;a<4;a++)
{
question=(rand()%4)+1;
if(question==1)
{
cout<<"What is 8+5 ";
cin>>option1;
if(option1==13)
{
score++;
cout<<"Correct answer"<<endl;
cout<<"Score ="<<score<<endl;
}
else
{
score--;
cout<<"Bad answer"<<endl;
cout<<"Score ="<<score<<endl;
}
}
if(question==2)
{
cout<<"What is 8+5"<<endl;
cin>>option1;
if(option1==13)
{
score++;
cout<<"Correct answer"<<endl;
cout<<"Score ="<<score<<endl;
}
else
{
score--;
cout<<"Bad answer"<<endl;
cout<<"Score ="<<score<<endl;
}
}
if(question==3)
{
cout<<"What is 8+4";
cin>>option2;
if(option2==12)
{
score++;
cout<<"Correct answer"<<endl;
cout<<"Score ="<<score<<endl;
}
else
{
score--;
cout<<"Bad answer"<<endl;
cout<<"Score ="<<score<<endl;
}
}
if(question==4)
{
cout<<"What is 8-5";
cin>>option3;
if(option3==3)
{
score++;
cout<<"Correct answer"<<endl;
cout<<"Score ="<<score<<endl;
}
else
{
score--;
cout<<"Bad answer"<<endl;
cout<<"Score ="<<score<<endl;
}
}
}
getch();
}
everything is working fine.the problem arises when a question repeats itself. what should i do to make sure a question is asked only once?
-
Instead of selecting a random question index on each iteration, put all possible question indices in an array. (Better yet, put data about the question and its answer in an array, instead of hard-coding each question.)
Then, start the program by shuffling the array and afterwards just step through it in order.
You can use std::random_shuffle for the shuffling.
-
Code:
main()
{
int option;
char array[5];
array[2]="5+6";
cout<<array[2];
cin>>option;
if(option==11)
{
cout<<"Good:";
}
getch();
}
Is this code correct?
If yes, how would I use rand() and srand() functions?
Thanks.
-
>> Is this code correct?
No. You can't assign a string to an array element that holds a character. Can you switch to using the string class?
Actually, CornedBee's solution is better in general, but it may be too advanced for you.
You could just have a bool variable for all four questions. If the bool is false and rand() picks that question, then ask it and set the bool to true. If the bool is true, skip the question and make sure you don't increment a.
-
I have written a quick program that generates pseudo-numbers.
Example:
Code:
#include <cstdlib>
#include <ctime>
#include <cctypes>
#include <iostream>
const char *names[] =
{
"Won",
"Too",
"Thrice",
"For",
"Phifth",
"Firstteen"
};
int main(void)
{
size_t max = sizeof(names)/sizeof(*names);
char c;
srand(time(NULL));
do
{
std::cout << names[rand()%max] << std::endl << "Do you wish to continue?";
std::cin >> c;
} while(std::toupper(c) != 'N');
return 0;
}