1. 有没有大神给我讲解一下这个猜数字小程序的算法(代码在里面)
这里哪有算法,就是循环,让人猜数字大小。电脑生成随机一个[1,100]中的数,人猜,输入的如果比随机值大就显示too big,小就too small,直到猜对为止。
2. c语言怎么使用随机函数rand编写一个猜数字的游戏程序
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10
main()
{
int i,a,b;
srand(time(0)); /*设置种子,并生成伪随机序列*/
while(~scanf("%d",&b))
{
for(i=0;i<N;++i) rand()%10;
a = rand()%100;
while(1)
{
if(a == b) {puts(" 恭喜你 猜对了 !\n***************\n"); break;}
else if(a > b) puts("你输入的数 小了!");
else puts("你输入的数 大了!");
scanf("%d",&b);
}
}
system("pause");
}
3. 猜数字游戏: 让系统随机生成一个1-100之间的随机数,循环录入猜数直到猜中为止
这是我写的语句:
staticvoidMain(string[]args)
{
Randomd=newRandom();
intnum=d.Next(1,100);//随机数
intnum1=0;//用来保存输入的数
Console.WriteLine("输入一个数");
while(true)
{
stringstr=Console.ReadLine();
int.TryParse(str,outnum1);
if(num1==0)
{
Console.WriteLine("输入有误,重新输入");
continue;
}
else
{
if(num1>num)
{
Console.WriteLine("数字大了,重新输入");
continue;
}
elseif(num1<num)
{
Console.WriteLine("数字小了,重新输入");
continue;
}
elseif(num1==num)
{
Console.WriteLine("正确");
break;
}
}
}
Console.Read();
}
4. 猜数程序.要完整的程序!(用rand产生一个随机数)
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
void
main()
{
int
m,s,t,flag;
char
ch;
for(;;)
{
flag=0;
s=0;
srand(time(0));
do
m=rand();
while(m<0||m>100);
cout<<"我已经想到了一个0-100的整数,请你猜猜看。"<<endl;
for(;;)
{
if(flag)break;
cin>>t;
s++;
if(t>m)
cout<<"你猜的数太大了。"<<endl;
else
if(t<m)
cout<<"你猜的数太小了。"<<endl;
else
{
cout<<"恭喜!你猜对了!你猜了"<<s<<"次"<<endl;
cout<<"还想玩吗?(Y/N)";
cin>>ch;
if(!(ch=='Y'||ch=='y'))
return;
else
flag=1;
}
}
}
}
5. 急求c语言 猜数字算法
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 4/*随机抽N个数*/
#define NUM 8/*NUM次猜数的机会*/
void detect(char s[])
{
int i,j,num;
int a,b;
char ch[N];
for(num=0;num<NUM;num++)
{
a=b=0;
printf("第%d次机会:",num+1);
for(i=0;i<N;i++)
{
ch[i]=getch();
if(ch[i]>='0'&&ch[i]<='9')
{
for(j=0;j<i;j++)
if(ch[i]==ch[j]) break;
if(j<i) i--;
else
{
putchar(ch[i]);
for(j=0;j<N;j++)
{
if(ch[i]==s[j])
if(i==j) a++;
else b++;
}
}
}
else
i--;
}
printf(" %dA%dB\n",a,b);
if(a==N)
{
printf("恭喜你答对了!\n");
break;
}
}
if(num==NUM)
printf("很遗憾,正确答案为:%s\n",s);
}
main()
{
int i,j;
char s[N+1];
srand(time(0));
for(i=0;i<N;i++)
{
s[i]=rand()%10;
for(j=0;j<i;j++)
if(s[i]==s[j]) break;
if(j<i) i--;
else
{
s[i]+='0';
putchar('*');
}
}
s[i]='\0';
printf("\n总共%d次机会\n",NUM);
detect(s);
}
6. C语言编程:编写一个猜数的游戏,系统自动产生一个随机数,你来猜,程序给出提示,直到猜对为止。
import java.util.*;
class Assignment8{
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
int x=(int)(Math.random()*100);//生成一个0~100的随机数
int y=-1;
System.out.println("已生成0~100的随机整数,请输入您所猜的数:");
while(x!=y)
{
y=sc.nextInt();
if(y>x)
{
System.out.println("输入的数过大");
}
else if(y<x)
{
System.out.println("输入的数过小");
}
}
System.out.println("正确!该随机数是"+x);
sc.close();
}
}
while循环的格式:while(表达式){语句;}
while循环的执行顺序:当表达式为真,则执行下面的语句,语句执行完之后再判断表达式是否为真,如果为真,再次执行下面的语句,然后再判断表达式是否为真……就这样一直循环下去,直到表达式为假,跳出循环。
例:
int a=NULL;
while(a<10){
a++;//自加
if(a>5)//不等while退出循环,直接判断循环
{break;//跳出循环}
}
结果:结束后a的值为6。