random numbers within a function c++ - c++

I am trying to better use and understand functions and in this case I need to figure out how to make this function in particular return 2 different random numbers.I have set up the ctime and can successfully call my function and make my variable(message) equal the random number but when I call it again and ask it to print out the newest random number they are both the same.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int RandomNumberGen (int x);
int main()
{
srand(unsigned(time(0)));
int Ran;
int message;
message = RandomNumberGen (Ran);
cout << "Number 1 " << message << endl;
message = RandomNumberGen (Ran);
cout << "Number 2 " << message << endl;
return 0;
}
int RandomNumberGen (int Ran)
{
unsigned int RandomNum = 0;
RandomNum = rand()%8 + 4;
return RandomNum;
}
As you can see I set the function to output a random number and write it on screen and then I call the same function again and write that one on screen(write the second # on screen).Yet every time I call the function both numbers are written on the screen as the same even though I am generating a random number each time.
I know this is a simple and easy task but please let me know if what I am attempting to do is possible or do I need another separate function for the 2nd number.
My end goal is to base a lot of events and things off of one random number function so I can essentially call the function for a random number and then let it determine what happens next.
I placed in the code as you asked.I hope this is what you meant.I appreciate all the help and am very grateful for the answers.I plan to be using this more so I will be sure to get it right for you guys!

You called srand in the function RandomNumberGen, which is called multiple times. That's wrong, srand should be called only once, try put it in main instead.
Or better, instead of the C library crandom functions, use the methods in random if that's available.

Take a look at this question and particularly the answer. It should clarify some things about srand() and rand()
I quote the answer:
Seed is usually taken from the current time, which are the seconds, as in time(NULL), so if you always set the seed before taking the random number, you will get the same number as long as you call the srand/rand combo multiple times in the same second.
Basically what you should do, is call srand() only once at the beginning of your application and not in the function. Because your function will be called twice at a very short interval. Almost all the time in the same second. Generating the same starting sequence for the rand() function

you shouldn't seed the random number generator with each call, but only once. your two calls to the function probably execute so fast that the value of time(null) is still the same, and the same seed will produce the same pseudo random sequence.
(btw., you should use null or NULL, not 0 for a null pointer, and you do not use the parameter you pass to your randomnumbergen function, so you could just remove it entirely.)

Related

Array Function. Would appreciate a little clarification

I have a question regarding a school lab assignment and I was hoping someone could clarify this a little for me. I'm not looking for an answer, just an approach. I've been unable to fully understand the books explanations.
Question: In a program, write a function that accepts three arguments: an array, the size of the array, and a number n.
Assume that the array contains integers. The function should display
all of the numbers in the array that are greater than the number n .
This is what I have right now:
/*
Programmer: Reilly Parker
Program Name: Lab14_LargerThanN.cpp
Date: 10/28/2016
Description: Displays values of a static array that are greater than a user inputted value.
Version: 1.0
*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void arrayFunction(int[], int, int); // Prototype for arrayFunction. int[] = array, int = size, int = n
int main()
{
int n; // Initialize user inputted value "n"
cout << "Enter Value:" << endl;
cin >> n;
const int size = 20; // Constant array size of 20 integers.
int arrayNumbers[size] = {5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}; // 20 assigned values for the array
arrayFunction(arrayNumbers, size, n); // Call function
return 0;
}
/* Description of code below:
The For statement scans each variable, if the array values are greater than the
variable "n" inputted by the user the output is only those values greater than "n."
*/
void arrayFunction(int arrayN[], int arrayS, int number) // Function Definiton
{
for (int i=0; i<arrayS; i++)
{
if (arrayN[i] > number)
{
cout << arrayN[i] << " ";
cout << endl;
}
}
}
For my whole answer I assume that this:
Question: In a program, write a function that accepts three arguments: an array, the size of the array, and a number n. Assume that the array contains integers. The function should display all of the numbers in the array that are greater than the number n .
is the whole assignment.
void arrayFunction(int[], int, int); is probably the only thing you could write. Note however that int[] is in fact int*.
As others pointed out don't bother with receiving input. Use something along this line: int numbers[] = {2,4,8,5,7,45,8,26,5,94,6,5,8};. It will create static array for you;
You have parameter int n but you never use it.
You are trying to send variable to the function arrayFunction but I can't see definition of this variable!
Use something called rubber duck debugging (google for it :) ). It will really help you.
If you have some more precise question, ask them.
As a side note: there are better ways of sending an array to the function, but your assignment forces you to use this old and not-so-good solution.
Would you use an if else statement? I've edited my original post with the updated code.
You have updated question, then I update my answer.
First and foremost of all: do indent your code properly!!!
If you do that, your code will be much cleaner, much more readable, and it will be much easier understandable not only for us, but primairly for you.
Next thing: do not omit braces even if they are not required in some context. Even experienced programmers only rarely omit them, so as a beginner you should never do so (as for example with your for loop).
Regarding if-else statement the short answer is: it depends.
Sometimes I would use if (note: in your case else is useless). But other times I would use ternary operator: condition ? value_if_true : value_if_false; or even a lambda expression.
In this case you should probably settle for an if, as it will be easier and more intuitive for you.
Aside from the C++ aspect, think about the steps you need to do to figure out if a number is greater than a certain value. Then do that for all the numbers in the array, and print out the number if it's greater than n. Since you have a 'for' loop, it looks like you already know how to do a loop and compare numbers in C++.
Also, it looks like in your arrayFunction you are trying to input values? You can't input a whole array's worth of values in a single statement like you appear to be trying (also, 'values' is not the name of any variable in arrayFunction, so that would not be recognized when you try to compile it).

Formula used for function rand() in c++

I want to know what is the formula used for generating random numbers using the rand() function in C++. At first I though it would return random numbers every time, but it does not.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
srand(9865);
cout << rand() << "\n";
return 0;
}
Here I thought that, maybe because of given seed number and that unknown formula, it will be showing same number.
But, when i removed "srand(9865);" and execute several times it is showing only "41" as output. Please explain me what is all going on here.
From http://linux.die.net/man/3/rand
"If no seed value is provided, the rand() function is automatically seeded with a value of 1. ", and "..These sequences are repeatable by calling srand() with the same seed value. "
You have to seed your random function with a non static seed every time. One simple but not so accurate solution is to seed it with the clock:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
cout << "Hello world!" << endl;
srand(time(NULL));
cout << rand() << "\n";
return 0;
}
The library specifications don't dictate the formula for the random number generator (it is up to the implementation). The only things specified are that things can be controlled via srand for consistent pseudo-random generation:
In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time (declared in header <ctime>). This is distinctive enough for most trivial randomization needs.
So:
If you initialize srand with a given seed, the following rand calls will be consistent across runs.
If you initialize srand with a time-based seed, the following rand calls will almost surely be different across runs.
If you do not initialize srand, the following calls to rand will use the default initial seed.
Note that in contemporary C++, you should avoid using these ancient functions. See the answers to this question.

Making a c file for a git repository

I'm extremely new to Ubuntu and PuTTY and putting a C++ file into it, but I'm having a problem with my C++ file. What I need the program to do is take a string entered from the Ubuntu side, put into the C++ program, and have it count how many strings are entered in and it sends back like so:
./myfile Supplying arguments now
Argument #0: ./myfile
Argument #1: Supplying
Argument #2: arguments
Argument #3: now
Number of arguments printed: 4
So, when I run my program down below, the program goes on forever and I can't step through it. What is causing it and why and/or what can I do to fix the problem?
#include <stdio.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int count = 0;
while (*argv[argc] != NULL)
{
count++;
}
cout << count << endl;
system("PAUSE");
return 0;
}
Your code is an infinite loop because your while loop always checks the same condition. That's because argc never changes in your code.
What you meant to write is while (*argv[count] != NULL). However, what you meant isn't correct either.
C doesn't check array boundaries. When you read past an array boundary, you will not necessarily encounter a 0 value. You will read random garbage data which is in memory at that place.
You don't need to count the number of arguments yourself, because you already have it in the variable argc.
So a better solution to iterate all the command line arguments would be a for loop which increments count from 0 to argc.

Rand() Returning Same Value With Every Function Call [duplicate]

This question already has answers here:
What's the Right Way to use the rand() Function in C++?
(5 answers)
Closed 9 years ago.
Whenever I call a specific method in my class file, I return a random value, but it then proceeds to return the same value each time that method is called again.
For example
int CommuterTrain::getRandNumber(int maximumValue)
{
srand(unsigned(time(NULL)));
int maximum = maximumValue;
return rand()%maximum+1;
}
void CommuterTrain::loadRiders()
{
int passengers = getRandNumber(350);
currentRiders += passengers;
if (currentRiders > maxCapacity) {
cout << "The train has reached capacity! \nSome people were left at the station."
<< endl;
currentRiders = maxCapacity;
}
else {
cout<<passengers<<" pax have entered the vessel"<<endl;
}
}
Let's say the generator produces a number of 215 pax. When I call the method again, it doesn't randomize again and I wind up with 215 every time.
Is the issue in the generator, or is it in the following method?
You keep reseeding it. With the same seed (assuming you have a computer that is newer than 1920 and can therefore execute your code in under a second†). Don't do that.
It means you keep regenerating and restarting the same pseudo-random sequence over and over again. Consequently, you keep pulling out the same first value in that sequence with each call to rand().
Seed only once in your program.
You could put the srand call in main, for example.
† It could take around a second provided you began execution just as a new second began. Integer logic and all that. Whatever.
Your problem is, that you're seeding the random engine with every call to your function:
int CommuterTrain::getRandNumber(int maximumValue)
{
srand(unsigned(time(NULL))); // <<< This line causes your problems
int maximum = maximumValue;
return rand()%maximum+1;
}
The current time() result is unlikely to change significantly in between calls to the getRandNumber() function.
You should call srand(time(NULL)) once outside your function instead (e.g. in your CommuterTrain class constructor, or even better from main() only).

how to properly write a benchmark program under release mode?

while running some benchmark programs, the wall clock may surprisingly give a very small duration, which is because of various compiler optimization like dead code elimination, loop unwinding... that optimize away the tested code.
I may add some "exterior depency" via static/volatile qualifier, but that's not always work.
Any idea?
Generally, adding "some "exterior depency" via static/volatile qualifier" will change the actual behavior, and timing so is not advised.
The way I generally make sure that code can be tested is by using argc (the first arg to main)
If I need a loop, I change the input data using argc. Also have some dummy calculated value that is dependant on the code and printed after the loops and timer to make sure the result can't be optimized out.
If your fill function can take a seed, you can also just use argc as part of the seed.
So if you have random test data, or a loop used to test your code, add argc to it.
Without knowing exactly what you are testing the best I can do is someting like
seed=argc; // the compiler cannot count on any value of argc
dummy=0;
total_time=0;
for (rep=0; rep < max_rep; ++rep)
{
for (i =0; i < max_array; ++i)
{
test_array[i]=seed+gen_random(); // Note use of seed
}
start=time_now();
dummy+=function_to_time(test_array); // this is what you are testing
end=time_now();
total_time+=end-start;
seed++; // change seed just to be extra paranoid
}
std::cout << "Time=" << total_time << " Dummy=" << dummy << std::endl;