猜数小游戏2

文章展示了两段C++代码,分别实现了一个简单的猜数游戏和一个进阶版,后者具有人工智能猜测功能。用户可以指定一个1到100的数字,程序通过提示(大、小或正确)来猜测数字。高能版使用二分搜索算法优化了猜测次数。
摘要由CSDN通过智能技术生成

      第二款猜数游戏的代码,这回儿的比较友好,和上一个不知怎么玩的相比,着实简单了些.优点是代码少了许多,缺点是只有一种难度.

      比原创low多了......

#include<bits/stdc++.h>

using namespace std;

int main()
{
	srand(time(0));
	int x=-1,ans=rand()%100+1,tms=0;
	while(x!=ans)
	{
		printf("I have a number from 1 to 100. Please have a guess: ");
		scanf("%d",&x);
		tms++;
		if(x<1||x>100) puts("The number is error.");
		else if(x>ans) puts("The number is larger than my number!");
		else if(x<ans) puts("The number is smaller than my number!");
		else puts("Oh, you are right!");
	}
	printf("You guessed it %d times.",tms);
 	return 0;
}

      上边的是让我们来猜,这个角色互换,让人工智障来猜:

      低能版:

#include<bits/stdc++.h>

using namespace std;

int main()
{
	srand(time(0));
	puts("Please think a number from 1 to 100. And then I'll guess it.");
	puts("If I guess right, you should say \"R\"(Right).");
	puts("If my guess is too large, you should say \"L\"(Large).");
	puts("If my guess is too small, you should say \"S\"(Small).");
	puts("DON'T TELL A LIE!\n");
	char c='\0';
	int tms=0;
	while(c!='R')
	{
		printf("I guess the number is %d.Is it right(R, L or S)? ");
		scanf("%c%*c",&c);
		tms++;
		if(c=='R') break;
	}
	printf("I guess it %d times!",tms);
 	return 0;
}

颇有人机之风...

高能版(糊弄不了了):

#include<bits/stdc++.h>
using namespace std;

int main()
{
	puts("Please think a number from 1 to 100. And then I'll guess it.");
	puts("If I guess right, you should say \"R\"(Right).");
	puts("If my guess is too large, you should say \"L\"(Large).");
	puts("If my guess is too small, you should say \"S\"(Small).");
	puts("DON'T TELL A LIE!\n");
	char c='\0';
	int tms=0,l=1,r=100;
	while(c!='R')
	{
		int t=l+r>>1;
		printf("I guess the number is %d. Is it right(R, L or S)? ",t);
		scanf("%c%*c",&c);
		tms++;
		if(c=='R') break;
		if(c=='L') r=t;
		if(c=='S') l=t;
		if(l>=r)
		{
			puts("You told a lie!");
			return 0;
		}
	}
	printf("I guess it %d times!",tms);
 	return 0;
}

一起来试试.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值