Hi im trying to make a maths program and im having trouble with one of my sections where im currently just using '+' incorporated in to a do while loop until the score = 10 though i'm stuck on how to make it randomly change the question between + or - as so far i've only got +

int choice ; 
    cin >> choice;
    do {
     int r, r2, answerplus, answersubtract;
     r = rand() % 8 + 1;  
     r2 = rand() % 8 + 1; 
     answerplus = r + r2;
     out << "question number " << questionumber << endl;
     cout << r <<  "+ __ = " << answerplus << endl;

      int responce; 
     cin >> responce;
     
     if (responce == r2)  {cout << "correct!" << endl;
     score = score + 1; }
     else {cout << "wrong!" << endl; }
     questionumber = questionumber + 1;
     cout << "your score is " << score << endl;
 while (questionumber <= 10);

thankyou

I think you need to describe what it is your making and what your is problem a little better. Simply saying i'm stuck isn't enough.

That looks like a fun little program. :) To make it do both addition and subtraction, you need to determine what changes between the two paths. Edward sees that you need to display a different character for the equation--either '+' or '-' so the user knows how to figure the answer--and the answer itself needs to reflect the right operation. If you hoist the operator character out into a variable, you can localize the choice between addition and subtraction without changing the rest of the code:

#include <cstdlib>
#include <ctime>
#include <iostream>

int main()
{
  using namespace std;

  srand(unsigned(time(0)));

  while (true) {
    int lhs = rand() % 8 + 1;
    int rhs = rand() % 8 + 1;
    int answer;
    char op;

    // Choose equally between + and -
    if (rand() % 2 == 0) {
      answer = lhs + rhs;
      op = '+';
    }
    else {
      answer = lhs - rhs;
      op = '-';
    }

    cout << lhs << ' ' << op << " __ = " << answer << "\n>";

    int choice;

    if (!(cin >> choice))
      break;

    if (choice == rhs)
      cout << "Correct!\n";
    else
      cout << "Incorrect, the answer is " << rhs << '\n';
  }
}

The choice is made by going one way if the random value is even, and the other way if it's odd. That gives you a good 50/50 chance for either addition or subtraction. You can change that so one has more probability than the other. For example, if you change rand() % 2 to rand() % 3, addition will be twice as likely.

This approach to making random decisions can be applied in a lot of places and can be extended for more than two paths. It's a good trick to have under your belt. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.