#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
usingnamespace std;
int main()
{
int numbers = 0;
int i,x,z,average,total = 0;
cout << setprecision(3);
cout << "Enter how many times you want to generate random numbers: ";
cin >> numbers;
cout << "\nThis number is also used to cover the range of random integers." << endl;
cout << "\nEnter a starting minimum number: " ;
cin >> x;
srand(time(0));
for (i = 1 ; i<numbers; i++)
{
z = rand () % numbers + (x+1);
cout << "Random " << (i+1) << ": " << z << endl;
total += z;
}
average = (total/i+1);
cout << "\nThe average is " << total << endl;
cout << "\nSum is " << total << endl;
cout << "\nThe maximum number is: ";
return 0;
}
2. Keep track of the largest random number so far as they're generated. In the for loop you can check if the newly generated random number is greater than the largest one you've seen so far.
3. You've defined the variable for average as an integer. If you want decimal points, it would need to be a double (or float). I'd also make total a double and initialize to 0.0 so you don't have integer division at line 30. Try using fixed in addition to setprecision(2).
So thanks to you I've solved number 2 but I can't figure out for the life of me how to find the greatest value produced by the RNG. Do I need an if statement?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
usingnamespace std;
int main()
{
int numbers = 0;
int i,x,z = 0;
double average, total = 0.0;
cout << setprecision(3);
cout << "Enter how many times you want to generate random numbers: ";
cin >> numbers;
cout << "\nThis number is also used to cover the range of random integers." << endl;
cout << "\nEnter a starting minimum number: " ;
cin >> x;
srand(time(0));
for (i = 0 ; i<numbers; i++)
{
z = rand () % numbers + (x+1);
cout << "Random " << (i+1) << ": " << z << endl;
total += z;
}
average = (total/i+1);
cout << "\nThe average is " << average << endl;
cout << "\nSum is " << total << endl;
cout << "\nThe maximum number is: ";
return 0;
}
Yes - you can use an if statement in the for loop to see if the newly generated random number is greater than the current max you have stored - if yes, then updated the max value stored.
Whatever variable you create to store the max value would be initialized so the first time through the for loop, you're comparing the random number to a valid value.