因此,作为uni工作的一部分,我必须创建一个彩票模拟器。我在这个程序中也使用了2个函数。 get_lotto_draw创建一个6元素数组,其随机数在1-49之间,find_matches应该将用户定义的6元素数组与此随机生成的数组进行比较,并跟踪找到的匹配项数。该程序模拟在用户指定的年数内每周播放一次乐透。
主体:
const int WEEKS_IN_YEAR = 52;
int lottoCounter = 0;
years = years * WEEKS_IN_YEAR;
int match1 = 0;
int match2 = 0;
int match3 = 0;
int match4 = 0;
int match5 = 0;
int match6 = 0;
for(lottoCounter = 0; lottoCounter < years; lottoCounter++)
{
int* x = get_lotto_draw(); //Use function to generate lottery numbers
int* y = userNums;
int found = find_matches(x, y);
if(found == 1)
{
match1++;
}
if(found == 2)
{
match2++;
}
if(found == 3)
{
match3++;
}
if(found == 4)
{
match4++;
}
if(found == 5)
{
match5++;
}
if(found == 6)
{
match6++;
}
if(match6 != 0)
{
printf("Congratulations Roger, you've won the Jackpot!");
break;
}
}
printf("Matched 1 number %d times", match1);
printf("\nMatched 2 number %d times", match2);
printf("\nMatched 3 number %d times", match3);
printf("\nMatched 4 number %d times", match4);
printf("\nMatched 5 number %d times", match5);
printf("\nMatched 6 number %d times", match6);
free(arrayPointer);
get_lotto_draw函数:
int* get_lotto_draw() //Returns an array of six random lottery numbers 1-49
{
int min = 1;
int max = 49;
int counter = 0;
srand(time(NULL)); //Set seed for rand as current time
int *arrayPointer = malloc(6 * sizeof(int)); //Clear space for arrayPointer
for(counter = 0; counter <= 5; counter++)
{
int x1 = 1;
while(x1)
{
int temp = rand()%(max-min)+min; //Gives random number range between 1-49 inclusive
int i = 0;
for(i = 0; i < counter; i++)
{
if( arrayPointer[i] == temp)
{
break;
}
}
if(i == counter)
{
x1=0;
arrayPointer[counter] = temp;
}
}
}
return arrayPointer;
}
find_matches功能:
int find_matches(int * array1, int * array2)
{
int* x = array1;
int* y = array2;
int found = 0;
int i = 0;
int j = 0;
for(i = 0; i < 6; i++)
{
for(j = 0; j < 6; j++)
{
if(x[i] == y[j])
{
found++;
}
}
}
return found;
}
我遇到的问题是“匹配的1个数字%d时间”等不起作用,它们只给我0个值。我认为这个问题主要是因为我的功能在早期工作。谢谢你的时间。
修改的
我将此代码添加到main:
int myArray[6] = {1, 23, 42, 32, 4, 17};
int* x = userNums;
int* y = myArray;
int found = find_matches(x, y);
printf("matches: %d", found);
这很好用。如果我输入myArray中存在的3个数字,则返回3,依此类推。
答案 0 :(得分:1)
所以我从我的问题留下的评论中得到了所有的建议。我将随机种子放在main的开头而不是函数中,修复了每年抽奖的次数,并在返回arrayPointer后放置free(arrayPointer)。实施所有这些修复程序后,我的程序现在运行正常,感谢所有贡献者!