Write a single C statement that declares an int variable randomGuess, and initia
ID: 3796335 • Letter: W
Question
Write a single C statement that declares an int variable randomGuess, and initializes it with a randomly generated odd number between LOWER_BOUND and UPPER_BOUND (inclusive). Assume that LOWER_BOUND and UPPER_BOUND are odd numbers declared as integer constants, and UPPER_BOUND is the larger value of the two.
The answer is int randomGuess = rand() % ((UPPER_BOUND - LOWERBOUND)/2 + 1)*2 + LOWER_BOUND;
I know this is the answer, but I am having trouble understanding it. For example, if UPPER_BOUND were 7 and LOWER_BOUND were 1, then int randomGuess would be rand() % 8 + 1. Doesn't that mean it just randomly generates a number between 8 and 1, instead of an odd number from 7 to 1? What am I missing here?
Explanation / Answer
int randomGuess = rand() % ((UPPER_BOUND - LOWERBOUND)/2 + 1)*2 + LOWER_BOUND;
Hi Friend, rand()%n :- function generates random number between 1 to n-1
rand() % 8:
generates random number : 0 to 7
rand() % 8 + 1:
generates random number : 1 to 8
Please let me know if still you have doubt
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.