猜猜游戏帮助需要随机数

时间:2014-10-05 16:34:24

标签: c if-statement random

因此,使用C我的代码存在问题。 还没有学会如何使用do / while命令。我从来没有看到让决赛正确。 我尝试编码显示随机(例如9) 我按9并说太低了。最后,随机数表示为14。 我不确定如何在用户的输入尝试中获得随机数一致。

// This is a guessing game. You have 4 attempts to guess the number between 1-20. 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){

    int usersInput;
    int range; 
    range = rand() %21;

    printf("Hello and welcome to my game! I have a number in my head between 1-20.\n");
    printf("Try and guess what it is.\n");
    printf("Please enter your guess as an integer.\n");
    scanf("%d", &usersInput);
// These are the cases for your first attempted
// Attempt 1
    if (usersInput > range) {
        printf("Your guess is too high. Please try again\n");
     }
    else if (usersInput < range){
        printf("Your guess is too low. Please try again\n");
     }
    else if (usersInput == range){
        printf("You are correct! Congratulations, you win!!\n");
    return 0;
    }
// Attempt 2        
    scanf("%d", &usersInput);
    if (usersInput > range){
        printf("Your guess is too high. Please try again\n");
    }
    else if(usersInput < range){
        printf("Your guess is too low. Please try again\n");
    }
    else if(usersInput == range){
        printf("You are correct! Congratulations, you win!!\n");
    return 0;
    }
// Attempt 3
    scanf("%d", &usersInput);
    if (usersInput > range){
        printf("Your guess is too high. Please try again\n");
    }
    else if(usersInput < range){
        printf("Your guess is too low. Please try again\n");
    }
    else if(usersInput == range){
        printf("You are correct! Congratulations, you win!!\n");
    return 0;
    }
// Attempt 4
    scanf("%d", &usersInput);
    if (usersInput > range){
        printf("Your guess is too high. You lose!\n");
        printf("the random number is %d \n", rand() %21);
    }
    else if(usersInput < range){
        printf("Your guess is too low. You Lose!\n");
        printf("the random number is %d \n", rand() %21);
    }
    else if(usersInput == range){
        printf("You are correct! Congratulations, you win!!\n");
        printf("the random number is %d \n", rand() %21);
        return 0;
    }
}

1 个答案:

答案 0 :(得分:3)

问题纯粹出现在您的输出中 - 您输出rand()的结果而不是您在开头确定的值range

printf("the random number is %d \n", rand() %21);

应该是

printf("the random number is %d \n", range);
相关问题