vendredi 24 juin 2022

C random number generator generating numbers not in the range

enter image description hereI was demonstrating a rock paper scissors game to a friend of mine when i came across this problem. The random number generation wouldn't work for me and I am looking for a solution to the problem.

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
void main()
{   int draw = 0;
    int user_win = 0, comp_win = 0;
    
    srand(time(0));
    int random,upper = 2,lower = 0;
    random = (rand()%(upper - lower + 1)) + lower;
    
    char comp_option,options[4] = {'r','p','s','\0'}, user_option[12];
    comp_option = options[random];
    for(int i=0; i<=5; i++){
    
    printf("%d\n%c",random,comp_option);
    printf("%s", "Enter your option ");
    scanf("%s", &user_option[12]);
    printf("computer choses: %s\n",comp_option == 'r' ? "Rock" : comp_option == 'p' ? "Paper" : "Scissor");
    
    if(strcmp(user_option,"rock") && comp_option=='s'){
        user_win+=1;
        }
    else if (strcmp(user_option,"scissor") && comp_option=='p'){
        user_win+=1;    
        }
    else if (strcmp(user_option,"paper") && comp_option=='r'){
        user_win+=1;
        }
    else if (strcmp(user_option,"scissor") && comp_option=='r'){
        comp_win+=1;
        }
    else if (strcmp(user_option,"rock") && comp_option=='p'){
        comp_win+=1;    
        }
    else if (strcmp(user_option,"paper") && comp_option=='s'){
        comp_win+=1;
        }
    else{
        draw+=1;
        }
}
    // decision 
    if(draw>comp_win && draw>user_win){
            printf("Match draw\n");
        }
    else if(comp_win>user_win){
        printf("Computer won the match\n");
        
        }
    else{ 
        printf("user won the match\n");
        }
    printf("User Score: %d\n", user_win);
    printf("Computer score: %d\n", comp_win);
    printf("Draws: %d\n",draw);    
    }

other improvements and ideas to the code are appreciated.




Aucun commentaire:

Enregistrer un commentaire