Write a program that will do the following steps:
- generate 2 random integer numbers between 0 and 20
- 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
rand() creates a random number between 0 and some big value named RAND_MAX. To get a random value between 0 and 20, you divide by 21 and take the remainder. The remainder or "modulus" function is done with % in C++ so it's random1 = rand() % 21;
The easiest way to do output with cout is the << operator. For example:
1 2
int i = 15;
cout << "the value of i is " << i << endl;
the value of i is 15
The << operator takes an output stream (ostream) on the left and an expression on the right. It formats the expresssion as needed and prints it out. These can be chained together. The final endl is a special "manipulator" then prints an end of line character and then "flushes" the stream, which pushes any buffered output to the device.
Okay, I think I have the rand() thing down.
Now for the cout part. I don't really know what to put inside of the cout <<.
Should I put something like
cout << "The two random numbers are ";
cout << "The average is";
cout << "The square root of is";
Line 13: random1 and random2 is actually a boolean expression. You want to print the string " and " instead. So it should be cout << "The two random numbers are " << random1 << " and " << random2 << '\n';
At lines 14 and 15, you should print the actual value of random1, not the string "random1". See if you can fix this yourself.
Line 16: Since you've already computed the average and stored it into a variable, just print the variable.