第二款猜数游戏的代码,这回儿的比较友好,和上一个不知怎么玩的相比,着实简单了些.优点是代码少了许多,缺点是只有一种难度.
比原创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;
}
一起来试试.