Write a program that will do the following steps:
- generate 2 random integer numbers between 1 and 20 inclusive ( 1-20, no 0 values)
- calculate the square root of each number
- calculate the average of the 2 numbers
- print the 2 random numbers
- print the square root of each random number with 3 digits after the decimal point
- print the average of the 2 numbers with 1 digit after the decimal point
Example program output:
The two random numbers are 2 and 3
The average is 2.5
The square root of 2 is 1.214
The square root of 3 is 1.372
#include <iostream>
#include <ctime> // Needed for the true randomization
#include <cstdlib>
#include<cmath>
#include<iomanip>
using namespace std;
int main ()
{
int xRan=0;
int xRan1=0;
double root1;
double root2;
double average;
srand( time(0)); // This will ensure a really randomized number by using computer clock
xRan=rand()%20 + 1; // Randomizing the number between 1-15.
xRan1=rand()%20 + 1;
cout << "The two random numbers between 1-20 are: " << xRan;
cout<<" and "<<xRan1<<endl;
return 0;
}
This is a “prove you’ve been paying attention in class” kind of homework.
You have generated two random numbers. You have printed them. That’s a third of your homework already done!
Is there a math function somewhere that can compute the square root of a number? (There is. Try Googling “c++ square root”.)
Use setw() manipulator to control the total field width (number of characters output) and setprecision() to control the number of digits appearing after the decimal point. Oh, don’t forget to use fixed before outputting any values.