【发布时间】:2019-09-25 12:16:06
【问题描述】:
我正在尝试编写一个模拟器来玩 强力球彩票,其中程序会要求输入 5 数字(又名白球)并输入到 6 元素数组中,然后另一个数字(红色强力球)进入6th 元素。
我需要弄清楚如何测试第一个 5 元素中的重复项,但 6th 不需要是唯一的。
我有一个我认为可以工作的循环,但它甚至没有执行,而且相当混乱。
是否有更有效的方法来测试重复项,可能涉及 bool 标志?
const int PBALLAMOUNT = 6;
const int PBMAX = 69;
const int PBMIN = 1;
const int REDMAX = 26;
cout << "Enter the numbers you want to use for the white powerballs" << endl;
for (int k = 0; k < PBALLAMOUNT - 1; k++)
{
cin >> pBallNums[k];
while (pBallNums[k] < PBMIN || pBallNums[k]>PBMAX)
{
cout << "Invalid input! Please enter different numbers between 1 and 69" << endl;
cin >> pBallNums[k];
}
}
bool dup = false;
for (int i = 0; i < PBALLAMOUNT - 1; i++)
{
for (int j = i + 1; j < PBALLAMOUNT - 1; j++)
{
while (!dup)
{
if (pBallNums[i] == pBallNums[j])
{
cout << "Please enter a unique number from the others in your PowerBall number selection" << endl;
cin >> pBallNums[i];
}
}
}
}
cout << "And what would you like for your redball" << endl;
cin >> pBallNums[5];
while (pBallNums[5] < PBMIN || pBallNums[5] > REDMAX)
{
cout << " The red powerball needs to be between 1 and 26: ";
cin >> pBallNums[5];
}
我基本上只需要它来提醒用户是否已经在数组中输入了一个数字并提供另一个std::cin >> pBallNums 语句,但实际结果在你输入数字后什么都没有发生。
【问题讨论】:
-
什么是
pBallNums?数组还是std::vector?pBallNums中值的顺序是否重要? -
std::any_of(和朋友)似乎是一个显而易见的工具……
-
考虑使用
std::set。保证套装中的所有物品都是独一无二的。 -
对收到的
set评论的好评感到惊讶。对于最多大小为 4 的列表,@JesperJuhl 的宣传会更有效率 -
@JeJo Neat 网站。以后得玩这个了。我所看到的是,对于基准测试来说,两者都执行得太快了。对于一些条目运行一次,这是意料之中的。
标签: c++ arrays algorithm duplicates user-input