vendredi 7 octobre 2022

How to generate a random mathematical operator

I have an assignment that requires me to make a quiz which generates random math questions. I'm fine with everything but i'm struggling to find a way to randomly choose between the mathematical operators "+" and "-".

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(){
    int choice = 0;
    int lives = 0;
    int question = 1;
    int a;
    int b;
    int answer = 0;
    int ans = 0;
    int correct = 0;
    printf("\n Welcome to Maths Tester Pro.");
    printf("\n Please Select a difficulty:");
    printf("\n 1) Easy");
    printf("\n 2) Medium");
    printf("\n 3) Hard \n");
    scanf("%d%*c",&choice);
    switch(choice)
    {
        case 1:
        printf("You have selected Easy mode!");
        lives = lives+3;
        while ((lives !=0)&&(question !=6)){
            if(question !=5){
                                    //Ask Question
                printf("\nQuestion %d of 5.  You have %d lives remaining", question, lives);
                srand(time(NULL));
                a = (rand() % (10 - 1 + 1)) + 1;    //make the sign random
                b = (rand() % (10 - 1 + 1)) + 1;
                printf("\n%d + %d = ",a ,b);
                scanf("%d", &answer);
                ans = a+b;
                                    //If answer is correct
                if((a+b) == answer){
                    printf("Correct!\n");
                    correct = correct + 1;
                }
                                    //If answer is incorrect
                else{
                    printf("Incorrect!  The correct answer was %d\n",ans);
                    lives=lives-1;
                }
                question = question + 1;
            }

In my code I have it written as ans=a+b but I want it to be able to randomly pick either "+" or "-".




Aucun commentaire:

Enregistrer un commentaire