Generating random integers, calculate the square root, calculate the average

Oct 31, 2014 at 7:29am
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

The average is 2.5

The square root of 2 is 1.214

The square root of 3 is 1.372
Oct 31, 2014 at 8:09am
What have you got so far?
Oct 31, 2014 at 8:47am
This is what I have. I'm not 100% sure on how to fill out the cout part
http://puu.sh/cxlvC/dbd5e97d7a.png
Oct 31, 2014 at 9:05am
in your includes:
do you mean <cstdlib> ?
btw, I think rand doesnt work that way.
See http://www.cplusplus.com/reference/cstdlib/rand/
there should be a modulus there somewhere.
:)
Last edited on Oct 31, 2014 at 9:05am
Oct 31, 2014 at 10:28am
Okay I fixed the <cstdlib> mistake.
I still don't get how to do rand and cout though :/
Oct 31, 2014 at 10:48am
Oct 31, 2014 at 10:59am
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.
Oct 31, 2014 at 6:43pm
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";
Oct 31, 2014 at 8:38pm
Yes, except follow the format given in the sample output of the assignment.
Oct 31, 2014 at 11:36pm
Alright boys!
How does this look :-)
http://gyazo.com/e9ff5ad10ca76aca376717314696845e
Nov 1, 2014 at 1:37pm
Very close.

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.
Topic archived. No new replies allowed.