我正在创建一个比较两个数组的程序;第一个数组,用户输入5个整数。在第二个数组中,计算机随机选择5个数字(两个数组都在0和9之间)。
我需要比较每个数组的元素以查看它们是否匹配。如果它们匹配,我将1添加到计数器变量。
(例如用户输入0 2 2 9 6,计算机[使用rand]选择2 3 2 9 0. elemnts 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
答案 0 :(得分:1)
没有必要在函数开始时“预先声明”所有变量。
如果您希望变量“重置”,请在循环内将变量声明移动到您使用它们的位置:
for (int i=0;i<play_amt;i++)
{
int total = 0; // A new variable 'total', that starts at 0 each time through the loop.
答案 1 :(得分:1)
你应该养成委派任务到函数的习惯。您遇到total
问题,因为您的main()
功能太长,很难跟踪该变量发生的情况。如果您的for
循环如下所示,那么您将遇到更少的麻烦:
for (i=0;i<play_amt;i++)
{
read_choices(user_choice);
choose_random(com_coice);
display_choice(com_choice);
total = count_matches();
cout<<"User matched "<<total<<"times"<<endl;
total_amt += evaluate_scenario(total, bet_amt);
} // end for loop