【发布时间】:2013-12-16 04:49:04
【问题描述】:
我正在创建一个比较两个数组的程序;第一个数组,用户输入 5 个整数。第二个数组,计算机随机选择 5 个数字(两个数组都在 0 和 9 之间)。
我需要比较每个数组的元素,看看它们是否匹配。如果它们匹配,我将 1 添加到计数器变量。
(例如用户输入 0 2 2 9 6,计算机 [使用 rand ] 选择 2 3 2 9 0。元素 3 和 4 匹配,所以这是两个。现在每个匹配都有不同的场景)
我的问题:用户还输入了他们想要比较这些数组的次数(这是一个名为 pick 5 的游戏)。 每次循环时我都需要将计数器重置为零我尝试使用 flush 命令,但它不起作用。
有什么想法吗?
int main ()
{
string name;
float total_amt, bet_amt, win_amt;
int play_amt, user_choice[5] = { }, com_choice[6], i, total=0;
int size = 5;
srand((unsigned)time(0));
cout<<"Welcome to pick 5, where the odds are never in your favor!"<<endl;
cout<<"What is your name?"<<endl;
cin>>name;
cout<<"How much money do you have?"<<endl;
cin>>total_amt;
cout<<"How much money would you like to bet?"<<endl;
cin>>bet_amt;
cout<<"How many times would you like to play?"<<endl;
cin>>play_amt;
for (i=0;i<play_amt;i++)
{
cout<<"Pick 5 integers between 0 & 9 "<<endl;
cin>>user_choice[0];
cin>>user_choice[1];
cin>>user_choice[2];
cin>>user_choice[3];
cin>>user_choice[4];
com_choice[0] = (rand()%9);
com_choice[1] = (rand()%9);
com_choice[2] = (rand()%9);
com_choice[3] = (rand()%9);
com_choice[4] = (rand()%9);
cout<<com_choice[0];
cout<<com_choice[1];
cout<<com_choice[2];
cout<<com_choice[3];
cout<<com_choice[4];
if (user_choice[0]==com_choice[0])
{
total++;
}
if (user_choice[1]==com_choice[1])
{
total++;
}
if (user_choice[2]==com_choice[2])
{
total++;
}
if (user_choice[3]==com_choice[3])
{
total++;
}
if (user_choice[4]==com_choice[4])
{
total++;
}
cout<<"User matched "<<total<<"times"<<endl;
// scenarios
if (total>=0 &&total<3)
{
total_amt-=bet_amt;
cout<<"Less than 3 of your numbers matched, tough luck"<<endl;
cout<<"You now have $"<<total_amt<<"dollars left."<<endl;
}
else if (total == 3)
{
cout<<"You matched 3 and broke even"<<endl;
}
else if( total == 4)
{
win_amt = bet_amt*2;
total_amt = total_amt + (win_amt - bet_amt);
cout<<"Congrats! you matched 4!!"<<endl;
cout<<"You now have $"<<total_amt<<"dollars!"<<endl;
}
else
{
win_amt = bet_amt*5;
total_amt = total_amt + (win_amt - bet_amt);
cout<<"WINNER WINNER YOU MATCHED 5!!"<<endl;
cout<<"You now have $"<<total_amt<<"dollars!"<<endl;
}
// end nested if-else
} // end for loop
} // end main
【问题讨论】:
-
不确定我是否完全理解,没有称为“计数器”的变量。你不想设置total=0吗?在“for”循环的开头?
-
正如答案所说,移动变量是好方法。如果您发现自己需要重置某些东西是有充分理由的,
var = {};通常会很好地完成。 -
对不起,我的计数器变量是“total”,我通过在循环中声明一个新的总变量来修复它。