random numbers help

im a beginner in c++, i need to write a program keeps generating two random numbers between 2 and 9 and asks the user for the product of the two numbers. Generate 5 such pairs of numbers and get the answers from the user.



so far i have. i know it might be wrong. just need some pointers
#include <iostream>
#include <cmath>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main ()

{

int a, b, answer, guess;

{
srand (time(NULL));
a = (2 + rand() ) % (9 - 2 + 1);

b = (2 + rand() ) % (9 - 2 + 1);
\\ (low + ran() % (high - low + 1)


cout <<"What is" << a << " x " << b << endl;
cin >> guess;

answer = a * b;
if( answer != guess)
cout <<"wrong, correct answer is:" << a << " x " << b << " = " << answer << endl;

else if(answer == guess)
cout << "answer is correct" ;
@ham13

To get a random number between 2 and 9, try
1
2
a = (rand()%7 + 2);
b = (rand()%7 + 2);
and for getting the 5 pairs, add another variable, maybe named index, initialized to 0.
Then use a do/while loop,
1
2
3
4
5
do
{... \\ show problem
... get result;
index++;
} while (index!=5);
@whitenite1: Actually, his random was correct, just written oddly. Your code would generate a number between 2 and 8.

Generally, we write it like this:
a = rand()%8+2;
Using (9-2+1) makes no sense if you're using hardcoded numbers. If you want flexibility, use this:
1
2
int hi = 9, lo = 2;
a = rand()%(hi-lo+1) + lo; // Generates [lo, hi] 

Now, the range auto-adjusts and you can change hi & lo during runtime if needed.
@Gaminic

Yeah, I see I screwed up on the rand(). Forgot about that pesky zero, just went with the 7 + 2 = 9, top of scale. I like the way you set up the rand hi/lo numbers. I'll use it that way in some of my future programming endeavors.
Topic archived. No new replies allowed.