我试图建立一个彩票游戏,该彩票游戏要求用户3次输入并将其与随机数组绘制的数字进行比较。如果这些用户号码中的任何一个与数组中的数字匹配,则程序应打印出匹配的数字。
ive试图在我的主要功能中使用while循环来控制流程,但即时通讯仍存在编译问题
#include<iostream>
#include <ctime>
#include "array.h"
using std::cout; using std::cin; using std::endl;
const int sizeofArray = 20;
void assign(int wins[], int sizeofArray);
void draw(int sizeofArray, int wins[]);
bool check(int num1, int wins[], int sizeofArray);
void entry(int& userNum);
void printOut(int wins[], int num);
int main() {
srand(time(nullptr));
int user[sizeofArray];
cout << "Good luck with this weeks lotto drawing!" << endl;
int wins[sizeofArray];
assign(wins, sizeofArray);
draw(sizeofArray, wins);
int userInput;
entry(userInput);
bool win = check(userInput, wins, sizeofArray);
if (win)
cout << "you have won!" << endl;
printOut(wins, sizeofArray);
}
void assign(int wins[], int sizeofArray) {
for (int i = 0; i < sizeofArray; ++i)
wins[i] = 0;
}
void draw(int sizeofArray, int wins[]) {
int number = 0;
while (number < sizeofArray) {
int number = rand() % 100 + 1;
if (!check(number, wins, sizeofArray)) {
wins[number] = number;
number++;
}
}
}
bool check(int num1, int wins[], int sizeofArray) {
for (int j = 0; j < sizeofArray; j++) {
if (wins[j] == num1)
return true;
}
return false;
}
void entry(int& userNum) {
int j;
cout << "Enter your lottery number guess: ";
cin >> userNum;
cout << "Your number was " << userNum << endl;
}
void printOut(int wins[], int num) {
cout << "Winning numbers in lottery are" << endl;
for (int j = 0; j < num; ++j) {
cout << wins[j] << " ";
}
}
i
答案 0 :(得分:0)
您的draw方法将无限循环,因为您两次声明了条件变量,这导致++运算符应用于错误的变量
void draw(int sizeofArray, int wins[]) {
int number = 0; // <--- HERE
while (number < sizeofArray) {
int number = rand() % 100 + 1; // <--- AND HERE
if (!check(number, wins, sizeofArray)) {
wins[number] = number;
number++; //This will increase the inner variable number not the outer one
}
}
}
要解决此问题,只需更改变量名
void draw(int sizeofArray, int wins[]) {
int counter = 0; <---
while (counter < sizeofArray) { <---
int number = rand() % 100 + 1;
if (!check(number, wins, sizeofArray)) {
wins[number] = number;
counter++; <---
}
}
}
答案 1 :(得分:0)
让我们看一下draw()
:
void draw(int sizeofArray, int wins[]) {
int number = 0; //First variable of name number
while (number < sizeofArray) {
//new variable with name number is introduced, it shadows the first one
int number = rand() % 100 + 1; //<-----------------------+
if (!check(number, wins, sizeofArray)) { // |
wins[number] = number; // |
number++; //Here you actually increase this variable-+
}
}
}
所谓的阴影在这里发生,并且外部int number
永远不会在循环内部被修改。只需重命名其中之一,就可以了。
如果您想了解更多有关此内容的信息,请查看here。