-1

我的程序生成的数字是 999999999999999999999999999999999999。我如何让这个程序生成从 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");

}

4

3 回答 3

3

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

int y = rand() % 100 + 1;

要告诉他们还剩多少次尝试,您需要一行

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

在你的 while 循环结束时。

于 2013-11-11T23:07:29.033 回答
2

Several suggestions:

  1. No need to check that y > 0 and y < 100, that's true by construction after applying @MasterOfBinary's fix to do modulo 100 and add 1. However, make the modulo 99 if you want a result strictly less than 100.
  2. Your response messages are backwards. If a < y their guess is too small, not too large.
  3. The final else clause is useless, make the else if above it a plain else.
  4. The loopcount = loopcount + 9; statement isn't needed, the break; immediately after gets you out of the loop.
  5. You could replace the other loopcount statements with increment forms, either ++loopcount; or loopcount += 1;.
  6. Your prompt and response strings need newlines (\n) at the end.
于 2013-11-11T23:31:38.963 回答
1

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

#include <time.h>
...
srand(time(NULL));
于 2013-11-11T23:16:59.580 回答