【问题标题】:Guessing game help needing with random number用随机数猜游戏需要帮助
【发布时间】:2014-11-30 00:51:03
【问题描述】:

所以我在使用 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;
    }
}

【问题讨论】:

  • 顺便说一句,用户名的选择不错:)

标签: c if-statement random


【解决方案1】:

问题完全在于您最后的输出 - 您输出的是 rand() 的结果,而不是您在开始时确定的值 range

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

应该是

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

【讨论】:

  • 我总是得到 11 作为随机数
  • 在调用之前尝试初始化随机种子:srand (time(NULL)); - 详情请参阅this related question
  • +1 for Chris,回答 Chris 和一些有价值的见解:-)
  • 认为我明白了(时间(NULL));范围 = rand() %21;
  • @user3629249 假设您有一个随机数生成器,它生成从0255 的数字,并且您想要一个从0100 的数字。如果您使用%,您最终会使用055,而不是5699。所以你要做的就是循环并丢弃任何200 或更大的输入。
猜你喜欢
  • 1970-01-01
  • 2015-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-14
相关资源
最近更新 更多