Sorry if this question has been answered elsewhere, I did search but couldn't find what I was looking for.
Anyway, I am stuck on a university homework problem, the problem asks for me to create a script that randomly generates numbers between 0-99 and prints the number on a new line each time, and if the number just printed falls within the range 68-74 it should then print Done! on the next line and exit the script.
I was given a template with most of the code already done for me, it looks as such:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
/**
* Your solution must start from below this point. No code modifications WHATSOEVER are allowed ABOVE this point!
*/
/**
* Your solution must have finished by this point. No code modifications WHATSOEVER are allowed BELOW this point!
*/
return 0;
}
int getRandInt() {
return rand() % 100;
}
Anyway after a lot of messing around I finally got it to print a list random numbers rather than 1 random number infinitely. I did this using:
do
printf ("%d\n", getRandInt());
while (getRandInt());
I tried plugging in things like:
do
printf ("%d\n", getRandInt());
while (getRandInt() <68);
to see if it would at least only print random integers less than 68, but this just makes it print only 1 or 2 random numbers (sometimes with greater values than 68) instead of the huge list the previous code block prints.
Am I calling the right function? Should I be using a Do While loop? How do I set a range of numbers for the loop to exit and print "Done!"? Obviously I can't edit the code outside of the comments.
I am very new to coding and would appreciated any assistance with this problem.
Declare a another integer variable and call the function inside the loop. So every time the return value will be stored in that variable, use that variable for condition checking.
Try the following code snippet-
/**
* Your solution must start from below this point. No code modifications WHATSOEVER are allowed ABOVE this point!
*/
int ret;
do{
ret = getRandInt();
printf("%d\n",ret);
}while(!(ret >= 68 && ret <= 74));
printf("Done!\n");
/**
* Your solution must have finished by this point. No code modifications WHATSOEVER are allowed BELOW this point!
*/
From the above code, when the number falls between 68 to 74 it will print Done!
and exit the loop. If not (!(ret >= 68 && ret <= 74)
) it will continue and execute the loop till a number falls between 68 to 74.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments