win_main.cpp
/*
* Copyright (c) 2011, 烟台大学计算机学院
* All rights reserved.
* 作 者:解晓东
* 完成日期:2012 年 10 月 20 日
* 版 本 号:v1.0
*
* 输入描述:输入一个整数
* 问题描述:猜数字游戏,可以1个人或两个人玩
* 程序输出:输出对错
* 问题分析:随机数的实现
* 算法设计:
*/
# include <iostream>
using namespace std;
int main()
{
int shu;
extern int cai_1(void);
extern int cai_2(void);
fanhui_1: //标记fanhui位置
cout<<"欢迎来到猜数字!\n";
cout<<"请输入玩家数(1/2)"<<endl; //提示输入一个数字
cin>>shu; //输入数字
if(1 == shu) //判断几个人玩,调用不同函数
{
system("cls"); //用于系统清屏
cai_2(); //调用函数
}
else if(2 == shu)
{
system("cls");
cai_1(); //调用函数
}
else
{
cout<<"请输入有效玩家数!\n";
system("cls");
goto fanhui_1; //返回标记处顺序执行
}
return 0;
}
cai_1.cpp
# include <iostream>
using namespace std;
int cai_1(void)
{
int val;
int temp;
char p;
do //循环,直到猜对
{
cout<<"请输入一个数让她/他猜:";
cin>>val;
system("cls"); //系统清屏
fanhui: //标记返回
cout<<"你猜猜看呀:";
cin>>temp;
if(temp>val) //判断是否正确,并输出相应的提示
{
cout<<"太大啦~"<<endl;
goto fanhui; //返回
}
else if(temp<val)
{
cout<<"有点小~"<<endl;
goto fanhui;
}
else if(temp == val)
{
cout<<"恭喜你猜对啦!\n";
system("pause"); //暂停,按任意键继续
system("cls");
cout<<"是否想继续猜呀?想,请输入 y/Y : ";
cin>>p;
system("cls");
}
else
cout<<"请输入有效整数!\n";
}while('y' == p||'Y' == p);//循环结束
return 0;
}
cai_2.cpp
#include<iostream.h>
#include<stdlib.h>//必须有
#include<time.h>//time的初始化
int cai_2(void)
{
bool flag=true;
char ch_2;
do
{
system("cls");
flag = true;
srand((unsigned int)(time(NULL))); // 初始化随机种子。
int num=rand()%1000+1;//产生1~1000的随机数,否则猜数字就十分困难了
int yournum;
while(flag)
{
cout<<"请猜数字,范围1~1000:";
cin>>yournum;
if(yournum>num) // 这样写比yournum-num>0少执行一个算术运算
{
cout<<"比我的数字大哦!"<<endl;
}
else if(yournum == num) // 这样写比yournum-num==0少执行一个算术运算
{
cout<<"你猜对啦!"<<endl;
flag=false;//猜对了修改标志,跳出循环
}
else
{
cout<<"比我的数字小哦!"<<endl;
}
}
cout<<"是否继续?(Y/N)"<<endl;
cin>>ch_2;
}while('Y' == ch_2 || 'y' == ch_2);
return 0;
}
总结:
新建一个项目文件,把3个cpp文件分别添加进去,编译连接运行;
extern 提前声明引用一个变量。