猜数游戏

计算机随机出一个数,然后用户猜,如果猜对了,则输出结果,如果猜错了,输出猜大或者小了。

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int magic;/*计算机想的数*/
    int guess;/*用户猜出的数*/
    magic=rand()%100+1;
    printf("please input the number of you guess\n");
    scanf("%d",&guess);
    if(guess>magic)
    {
        printf("wrong,too big!\n");
    }
    else if(guess<magic)
    {
        printf("wrong, too small\n"); 
    }
    else
    {
        printf("right\n");
        printf("the number id:%d\n",magic);
    }
    return 0;   
} 

本程序只能猜一次。所以修改下,直到猜对为止。程序如下

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int magic;/*计算机想的数*/
    int guess;/*用户猜出的数*/
    int count=0;/*记录猜的次数*/ 
    magic=rand()%100+1;
    do{
    printf("please input the number of you guess\n");
    scanf("%d",&guess);
    count++;
    if(guess>magic)
    {
        printf("wrong,too big!\n");
    }
    else if(guess<magic)
    {
        printf("wrong, too small\n"); 
    }
    else
    {
        printf("right\n");
    }
      }while(guess!=magic);
    printf("the number is:%d\n",magic);
    printf("the times is :%d\n",count);
    return 0;   
} 

本程序虽然做到了直到猜对为止,但是每次机器想的都是一样的。因为rand()函数是个伪随机数。
为了修改下。设置随机化数字,用time函数。

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
    int magic;/*计算机想的数*/
    int guess;/*用户猜出的数*/
    int count=0;/*记录猜的次数*/ 
    srand(time(NULL));
    magic=rand()%100+1;
    do{
    printf("please input the number of you guess\n");
    scanf("%d",&guess);
    count++;
    if(guess>magic)
    {
        printf("wrong,too big!\n");
    }
    else if(guess<magic)
    {
        printf("wrong, too small\n"); 
    }
    else
    {
        printf("right\n");
    }
      }while(guess!=magic&&count<10);/*最多猜10次*/
    printf("the number is:%d\n",magic);
    printf("the times is :%d\n",count);
    return 0;   
}

程序可以多次猜,如果猜数结束还可以进行下一次

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
    int magic;/*计算机想的数*/
    int guess;/*用户猜出的数*/
    int count=0;/*记录猜的次数*/ 
    char reply;
    srand(time(NULL));
    do{
    magic=rand()%100+1;
    do{
    printf("please input the number of you guess\n");
    scanf("%d",&guess);
    count++;
    if(guess>magic)
    {
        printf("wrong,too big!\n");
    }
    else if(guess<magic)
    {
        printf("wrong, too small\n"); 
    }
    else
    {
        printf("right\n");
    }
      }while(guess!=magic&&count<10);/*最多猜10次*/
    printf("the number is:%d\n",magic);
    printf("the times is :%d\n",count);

    printf("do you want to continue(Y/N or y/n)\n");
    scanf(" %c",&reply);
      }while((reply=='Y')||(reply=='y'));
    return 0;   
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值