#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <time.h>
using namespace std
//猜测最大次数
const int MAX_GUESS_TIME= 8
void ShowMenu()//显示菜单
void ShowGameInfo()//显示游戏简介
string GetNum()//产生一个不包含重复数字的四位数氏宽喊
string CalcResult(string strResult, string strInput)//比较两个数,输歼野出?A?B结果
bool CheckInput(string strInput)//检查输入有效性,简单处理,可增加其它判断
int main()
{
string strResult
string strInput
int iGuessTime=1
cout<<"==***欢迎使用猜数字游戏***=="<<endl
ShowMenu()
cin>>strInput
while (1)
{
if (strInput == "1")
{
break
}
else if (strInput == "2")
{
ShowGameInfo()
}
else if (strInput == "0")
{
cout<<"谢谢使用,再见!\n"
return 0
}
else
{
cout<<"对不起,请输入正确的数字!\n"
}
ShowMenu()
cin>>strInput
}
srand(time(NULL))
strResult = GetNum()
cout<<"请输入四位数(输入exit退出):"<<endl
cin>>strInput
while (strInput != "exit")
{
if (!CheckInput(strInput))
{
cout<<"您的输入不正确,请输入4位数字,不能有重复\n"
cin>>strInput
continue
}
if (strResult == strInput)
{
cout<<"哈!猜对了,你好棒!数字是:"<<strResult<<endl
cout<<"继续?(y/n)"
cin>>strInput
if (!(strInput[0]=='y' || strInput[0]=='Y'))
{
break
}
strResult = GetNum()
iGuessTime=1
}
else
{
if (MAX_GUESS_TIME >iGuessTime)
{
cout<<"第 "<<巧余iGuessTime<<"次猜测,输入"<<strInput<<",结果:"<<CalcResult(strResult, strInput)<<endl
++iGuessTime
}
else
{
cout<<"对不起,您猜得不对,数字是:"<<strResult<<endl
cout<<"继续?(y/n)"
cin>>strInput
if (!(strInput[0]=='y' || strInput[0]=='Y'))
{
break
}
strResult = GetNum()
iGuessTime=1
}
}
cout<<"请输入四位数(输入exit退出):"<<endl
cin>>strInput
}
cout<<"谢谢使用,再见.\n"
return 0
}
string GetNum()
{
char cTmp[2] = {0}
string strTmp
int iTmp=0
while (strTmp.length() != 4)
{
iTmp = rand() % 10
itoa(iTmp, cTmp, 10)
int iIndex = strTmp.find(cTmp)
if ( iIndex <0)
{
strTmp += cTmp
}
}
return strTmp
}
string CalcResult(string strResult, string strInput)
{
int iA=0,iB=0
int i=0,j=0
char cResult[5]={0}
for (i <strResult.length()++i)
{
for (j=0j <strInput.length()++j)
{
char strA=strResult[i]
char strB=strInput[j]
if (strA == strB)
{
if (i == j)
{
++iA
}
else
{
++iB
}
}
}
}
sprintf(cResult,"%dA%dB", iA, iB)
return cResult
}
bool CheckInput(string strInput)
{
int i=0
if (strInput.length() != 4)
{
return false
}
for (i <4i++)
{
char cTmp = strInput[i]
if ( cTmp >'9' || cTmp <'0')
{
return false
}
}
return true
}
void ShowMenu()
{
cout<<"请输入对应数字进行选择"<<endl
cout<<"1-->玩游戏"<<endl
cout<<"2-->游戏介绍"<<endl<<endl
cout<<"0-->退出游戏"<<endl
}
void ShowGameInfo()
{
cout<<"这里是游戏介绍,输入你自己的游戏介绍\n"
system("pause")
}
1、直接用数族纳滚悔转换到字符串的方法即可。sprintf(s,"%lf",a)s是字符数组,a是double。这兆备没样就把a写到s中了。2、例程:#include#includeusing namespace stdint main(){char s[12]double a=123456789876sprintf(s,"%lf",a)printf("%s",s)return 0}欢迎分享,转载请注明来源:内存溢出
评论列表(0条)