208k views
0 votes
PLEASE HELP!!

If smallestVal is 30 and greatestVal is 80, the number of possible values is 51 since 80 - 30 + 1 = 51. rand() % 51 generates an integer in the range of 0 to 50. Adding smallestVal (30) yields a range of 30 to 80. This sequence of operations is performed three times.

how would I code this in c++?

1 Answer

4 votes

Answer:

Step-by-step explanation:

Here's an example code in C++ that performs the sequence of operations you described three times:

#include <iostream>

#include <cstdlib>

#include <ctime>

using namespace std;

int main() {

// Seed the random number generator with the current time

srand(time(NULL));

int smallestVal = 30;

int greatestVal = 80;

int range = greatestVal - smallestVal + 1;

// Generate and print three random numbers in the range of 30 to 80

for (int i = 0; i < 3; i++) {

int randomNumber = rand() % range + smallestVal;

cout << "Random number " << i+1 << ": " << randomNumber << endl;

}

return 0;

}

This code uses the srand function to seed the random number generator with the current time. Then it calculates the range of possible values by subtracting the smallest value from the greatest value and adding 1. It then enters a loop that generates and prints three random numbers in the range of 30 to 80, using the % operator to ensure that the random number falls within the range and adding smallestVal to shift the range to start at 30.

User RyanFrost
by
8.3k points