Home > Enterprise >  Create program Random
Create program Random

Time:12-01

i want to randomize this program that recreates a quiz

I tried to add the rand function but I don't know how to proceed

#include <stdio.h>


int main(void) {
    int domanda, punti=0;

    puts("Quiz sul Riscaldamento Globale\n Otterrai 1 punto per ogni risposta esatta e 0 per ogni risposta sbagliata o non valida\n");

    puts("D1) Secondo il tredicesimo Obiettivo di Sviluppo Sostenibile, la minaccia piu' grande allo sviluppo e'/sono:\n");

    puts("[1] I cambiamenti climatici\n"
           "[2] L'inquinamento \n"
           "[3] Lo scioglimento della calotta glaciale polare \n"
           "[4] La crescita demografica\n");

    scanf("%d", &domanda);

    if(domanda == 1){
        puts("risposta corretta\n");
        punti = punti   1;
    }else{
        puts("risposta sbagliata\n");
        punti= punti   0;
    }

    puts("D2) Il tempo e il clima sono la stessa cosa.");
    puts("[1] Vero \n"
           "[2] Falso \n");

    scanf("%d", &domanda);

    if(domanda == 2){
        printf("risposta corretta\n");
        punti =punti   1;
    }else{
        printf("risposta sbagliata\n");
        punti= punti   0;
    }

    printf("hai fatto un punteggio di %d su 2", punti);

}

to work it works but I don't understand how to add the random if anyone knows how to do it help me thanks.

CodePudding user response:

A rand() function is available in C standard library: man 3 rand. If you want to explore random number generation, check random.org.

As is, your program is not designed to support randomness: Questions and answers are hard-coded. A first step to make it randomizable would be to store them into a variable. For instance (with correct answer always at first position, end of questions identified with NULL, end of answers of a question identified with NULL, maximum of nine answers per question):

struct {
   char * question;
   char * answers[10];
} qa[] = {
   {
      "Secondo il tredicesimo Obiettivo di Sviluppo Sostenibile, la minaccia piu",
      {
         "I cambiamenti climatici",
         "L'inquinamento",
         "Lo scioglimento della calotta glaciale polare",
         "La crescita demografica",
         NULL,
      }
   },
   {
      "Il tempo e il clima sono la stessa cosa.",
      {
         "Falso",
         "Vero",
         NULL,
      }
   },
   { NULL, NULL }
};

A program using this variable would then count the number of questions, take one randomly, then display the answers randomly and remember what is the display index of the correct one.

  •  Tags:  
  • c
  • Related