First write a function f to generate and return a random number between 0 to 100 In the main function, you keep calling function f until the returned value is less than 10 Then you should print out how many times the function f has been called. Note that every time f will only return a single random number, and the declaration of f is as follows: int f() For instance, if f returns 23, 89, 10, 1, then your program should print 4 on the screen.
- First write a function f to generate and return a random number between 0 to 100
- In the main function, you keep calling function f until the returned value is less than 10
- Then you should print out how many times the function f has been called.
- Note that every time f will only return a single random number, and the declaration of f is as follows:
- For instance, if f returns 23, 89, 10, 1, then your program should print 4 on the screen.
C++ language
Hint 1. You can implement the function using different methods, like the static variable
Hint 2. You can use the modular operator to shrink the generated random value, i.e., random() % 101 will guarantee the result is between 0 and 100.
#include<iostream>
#include<ctime>
using namespace std;
int f(){
return rand()%101; //return a random value in range of 0 to 100
}
int main()
{
srand(time(0)); //for generating different random numbers for every time you execute program
int count=1; //count of the number of random values lesser than 10
int number=f(); //generate a random mumber
cout << number <<"\t"; //display the random number
while(number>=10){ //repeat the loop if number generated is greater than or equal to 10
count++; //increment count
number=f(); //generate another random number
cout << number << "\t"; //display it
} //end the loop if number is less than 10
cout << "\n" << count << endl; //display the count
return 0;
}
Step by step
Solved in 2 steps with 1 images