### Question about doubles and rand.

Hello all, I tried a search and I wasn't able to find much. I apologize if a topic like this already exists.

I'm writing a program that requires the user to input two values. It then generates a random number between the two of them. One of the requirements of the assignment however is that the numbers input have to be stored as doubles and not ints. But when I do that it gives me a build error on my rand function. Here is the portion of my code where this occurs. Any help would be appreciated!

 ``1234567891011121314151617181920212223242526`` ``````#include #include #include #include #include using namespace std; int main() { /*How can I make max_number and min_number doubles and generate a random number between them?*/ int max_number; cout << "Maximum number: "; cin >> max_number; int min_number; cout << "Minimum number: "; cin >> min_number; /*This was how our text book told us to do rand between two values*/ double rand_number = rand() % (max_number - min_number + 1) + min_number; return 0; }``````
Last edited on

I'm doing my best to try and understand how this can help me, but I'm drawing a blank!

Edit: I think you're trying to tell me that I need to add the remainder to my variable, but from that reference it looks like you have to use doubles or floats in the function, which again leads back to my original problem.
Last edited on
fmod is the same as % but for double and floats
 ``123456789101112131415`` ``````#include #include #include using namespace std; int main(void){ double aDouble(8.0),bDouble(3.0); int aInt(8), bInt(3); cout << aInt << "%" << bInt << " = " << aInt%bInt << endl; cout << "fmod(" << fixed << aDouble << "," << bDouble << ") = " << fmod(aDouble,bDouble) << endl; bDouble = 3.3; cout << "fmod(" << aDouble << "," << bDouble << ") = " << fmod(aDouble,bDouble) << endl; return 0; }`````` ```\$ ./a.out 8%3 = 2 fmod(8.000000,3.000000) = 2.000000 fmod(8.000000,3.300000) = 1.400000```
Last edited on
How would I got about integrating that into my rand function?
I tried this:

 ``12`` ``````double rand_number = fmod(rand(), (max_number - min_number + 1) + min_number); // Random value between max and min numbers ``````

But it just totally borked up my results. So I think I might be confused.

Edit: I think I got it to work! Just had to move the '+ min_number' outside the function.

`double rand_number = fmod(rand(), (max_number - min_number + 1)) + min_number; `

Thank you for your help :)
Last edited on
Topic archived. No new replies allowed.