C猜猜比赛

时间:2013-11-11 23:01:57

标签: c

我的程序生成的数字是99999999999999999999999999999999999999.如何让这个程序生成1到100之间的数字。我如何告诉用户他们剩下多少次尝试?

#define _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>

int main()
{

int loopcount = 0;

int y = rand()%10;  

int a;

printf("You have 8 chances to guess the right number. Enter your first number.");

while ((loopcount < 9) &&(y>0) &&(y<100))
    {
    printf("enter a number.");
    scanf("%d", &a);
    if (a == y){
        printf(" you have guessed the correct number.");
        loopcount = loopcount + 9;
        break;
        }
    else if (a < y){
        printf("the number is less than");
        loopcount = loopcount + 1;
        continue; 
    }
    else if (a > y){
    printf("the number is greater");
        loopcount = loopcount + 1;
        continue;
    }
    else{
        printf("nothing.");
        break;
    }

}

system("pause");

}

3 个答案:

答案 0 :(得分:3)

要生成1到100(含)之间的数字,请使用以下命令:

int y = rand() % 100 + 1;

要告诉他们剩下多少次尝试,你需要一行

printf("Number of tries: %d", 9 - loopcount);

在你的while循环结束时。

答案 1 :(得分:2)

几点建议:

  1. 无需检查y > 0y < 100,这是真的 应用@ MasterOfBinary修复后进行构造,进行模100并添加1。 但是,如果您希望结果严格小于100,请使模99。
  2. 您的回复消息是倒退的。如果a < y他们的猜测也是如此 小,不太大。
  3. 最终的else条款没用,请将else if高于它 普通else
  4. 不需要loopcount = loopcount + 9;语句 在你离开循环后立即break;
  5. 您可以使用增量替换其他loopcount语句 表单,++loopcount;loopcount += 1;
  6. 您的提示和响应字符串最后需要换行符(\n)。

答案 2 :(得分:1)

如果您不为随机数生成器播种,rand将始终生成相同的数字序列。要播种它,请使用srand功能。播种它的规范方法是从一天中的时间开始,例如:

#include <time.h>
...
srand(time(NULL));
相关问题