Good attempt at a function like I was referring to, but it won't work this way because it doesn't know what r is until afterwards. Instead, you tell it the type of parameters it's working with, and then supply the parameters you want later. Also, I made a mistake by oversimplifying my explanation earlier. The reason it doesn't work properly is because rand() returns a number between 0 and the range of values, but never including the whole range itself. By a little mathematical trickery, however, we can force it to spit out values between x and y while including those values in the range of it's output. By subtracting the lowest from the highest and adding 1, we get the correct number of possible values, and adding the lowest value desired back to that total results in the correct range no matter what values are involved.
So it should be more like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int randNum (int first,int last)
{
return rand() %(last-first+1)+first;
}
int main()
{
srand(time(0)); // to get new random numbers for each run
int first, last;
first = 0;
last = 9;
for (int r = 1; r <= 100; r+=10)
{
cout<<"The range for this row is: "<<first+r<<" to "<<last+r<<": ";
for(int c = 1; c <= 10; c++)
cout<<randNum(first+r,last+r)<<" ";
cout<<endl;
}
cout << endl;
return 0;
}
|
This should give you the output you want without altering main's primary code (I only altered the formatting slightly). BTW, the function at the beginning does not have to use the same variable names, it just needs to know the variable types. Using different names in the function part, such as using x and y would also work. The values are supplied when the function is called upon in your output, and then it returns the value it gets based on the math in the function before outputting.
EDIT: Also, the formula rand()%10+r you used would result in the correct values, but you were already supplying two parameters in your code, so it was easier and more practical to use two parameters in the function like my earlier example to avoid straying outside of your assignment boundaries by altering your code further, not to mention the code is more reusable this way. Anytime in the future that you make a program involving random numbers, you can keep the function and srand commands there while replacing the rest of the code with your new program, and call on
randNum(lowest,highest)
to get the range of values desired any time you need to. Similarly, you can create other functions that do other things you prefer not to muck with the details of to handle various tasks. Once you have them working properly, they can in turn be transplanted into new programs as needed. In this respect, the fact that the variable names don't have to be the same is an advantage.