mercredi 27 février 2019

Random math generator C++

I have to create a program that generates a random math quiz with random operators and numbers. The problems I'm having so far are with: Division - I need for the user to be able to input 2.5 for a question like 5/2. I tried using float and double but I'm not sure I was using them correctly. Looping - My program only asks one question and then quits. Positive Answers - The program also needs to be very simple, not including negative integers anywhere. I get problems like 3 - 6 which equals -3 and I'm not sure how to avoid this. Any advice would help a lot! Sorry for all the questions, I'm very new to C++

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main () {
    int a, b, q, answer;
    bool correct = false;

    do {
        srand(time(NULL));
        a = rand() % 21;
        b = rand () % 10;
        char op = "+-*/" [rand() % 4];

        cout << "What is " << a << " " << op << " " << b << "? (q to quit) ";
        cin >> answer;

        switch (op) {
            case '+':
                if (answer == a + b) correct = true;
                break;
            case '-':
                if (answer == a - b) correct = true;
                break;
            case '/':
                if (answer == a / b) correct = true;
                break;
            case '*':
                if (answer == a * b) correct = true;
                break;
        }

        if (correct == true) {
            cout << "Good job!" << endl;
        } else {
            cout << "Incorrect." << endl;
            }

        if (answer = 'q') {
            break;
        }
    } while (answer != 'q');
}

Aucun commentaire:

Enregistrer un commentaire