Reputation:
C++ beginner here with a problem using a functions. Please help!
I am trying to make a random number generator function that I can call from within int main to cout a randomly generated float between 0.0 and 1.0 to my screen. When I create the generator in int main and cout it runs fine and returns a float just the way I want, but when I put the same code in a function and call it in int main I get some mix of letters and numbers that makes no sense.
I understand that I could just use the code in the way it works and ignore it but at this point I really want to know why it's not working the way I'm trying to make it work. I've looked all over for the answer and feel as if I'm missing some really basic knowledge about the way functions work in C++.
Why is the code that works perfectly fine in int main returning gobbledygook when called from a function?
Random number generator in function (returns nonsense):
#include <iostream>
#include <random>
#include <ctime>
using namespace std;
float roll();
int main(){
cout<<roll<<endl;
system("PAUSE");
return 0;
}
float roll(){
default_random_engine generator;
uniform_real_distribution<float> distribution(0.0f,1.0f);
return distribution(generator);
}
Random number generator in int main (this one returns a float):
#include <iostream>
#include <random>
#include <ctime>
using namespace std;
int main()
{
default_random_engine generator;
uniform_real_distribution<float> distribution(0.0f,1.0f);
float roll = distribution(generator);
cout<<roll<<endl;
system("PAUSE");
return 0;
}
Upvotes: 0
Views: 161
Reputation: 182761
This is wrong:
cout<<roll<<endl;
You want:
cout<<roll()<<endl;
You want to call the function.
Upvotes: 2
Reputation: 500
You just put the name of function which means just the address of it. Call it by using as defined. For more information please check the tutorial.
#include <iostream>
#include <random>
#include <ctime>
using namespace std;
float roll();
int main(){
cout<<roll();<<endl;
system("PAUSE");
return 0;
}
float roll(){
default_random_engine generator;
uniform_real_distribution<float> distribution(0.0f,1.0f);
return distribution(generator);
}
Upvotes: 0