I have been thinking on this for a while. I was given this assignment that says the following:
There is a text file containing numbers. (MIN, MAX, NUMBER) I have to read the contents of the file, then generate a random number between MIN and MAX. If generated number matches the number, then print "Match."
MIN: 7 MAX: 17 NUMBER: 15 ...
I was able to read every number into an array, with this code:
int main(void)
{
srand(time(NULL));
int nums[50] = {0};
int i = 0;
FILE * fp;
/*if(fp == NULL) return 1;*/
if (fp = fopen("numbers.txt", "r")) {
while (fscanf(fp, "%d", &nums[i]) != EOF) {
++i;
}
fclose(fp);
}
for (--i; i >= 0; --i)
printf("num[%d] = %d\n", i, nums[i]);
return 0;
}
However, I have no idea how to continue. How can I assign the specific values to my random number generator function?
int random(int min, int max) {
return rand()%(max-min+1)+min;
}
if(fp == NULL) return 1;?? You just declared that variable on the previous line with indeterminate content. That line seems pretty worthless (and invokes undefined behavior as well).intvariables to read the data (minval, maxval, testval) from the current line.Then, usingminvalandmaxval, compute your random number and see if it is thetestval. If it is, report Match, otherwise, not. You can do it all inside one single-scanning for-loop.