C 用于比较int数组的程序不工作
因此,作为uni工作的一部分,我必须创建一个彩票模拟器。我在这个程序中也使用了2个函数。get_lotto_draw使用1-49之间的随机NUM创建一个6元素数组,find_matches应将用户定义的6元素数组与此随机生成的数组进行比较,并跟踪找到的匹配数。该程序模拟在用户指定的年数内每周玩一次乐透 主体:C 用于比较int数组的程序不工作,c,arrays,C,Arrays,因此,作为uni工作的一部分,我必须创建一个彩票模拟器。我在这个程序中也使用了2个函数。get_lotto_draw使用1-49之间的随机NUM创建一个6元素数组,find_matches应将用户定义的6元素数组与此随机生成的数组进行比较,并跟踪找到的匹配数。该程序模拟在用户指定的年数内每周玩一次乐透 主体: const int WEEKS_IN_YEAR = 52; int lottoCounter = 0; years = years * WEEKS_IN_YEAR; int match1
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);
这个很好用。如果我输入myArray中存在的3个数字,则Find将返回3,依此类推。因此我从我的问题留下的评论中得到了所有建议。我将随机种子放在main的开头,而不是函数中,固定每年抽奖的次数,并在返回arrayPointer后放置free(arrayPointer)。在实施了所有这些修复之后,我的程序现在运行良好,感谢所有的贡献者
match1
到match6
更好地生活在一个数组中,这将大大简化主体(<20行)。顺便说一句,内存泄漏。在循环中的get_lotto_draw()中使用malloc()内存,并且永远不会释放该内存到main()
的开头。它不应该在当前位置。@dat_guy根据您的更新,您的更改使内存泄漏更严重。首先——您正在调用free(*arrayPointer)但是释放它的正确方法是不解除对它的引用,因此这可能会导致崩溃。其次,您不能释放缓冲区,然后计划稍后使用其内容(这是通过返回指针来完成的)。把它放在别的地方,等你用完之后。你每年只会得到一次新的乐透抽奖。除此之外,移动srand
应该可以解决您的问题。
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;
}
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;
}
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);