2

So I need to randomly generate a double between 2 doubles, and in this specific case, it is to randomly generate a GPA. I tried at first to do this:

srand(time(NULL));

double rands1 = rand() % (4) + ((rand() % (10)) / 10.0);

And this does work... mostly. I can get anywhere from a 0.0 to 3.9, but it has to be from 0.0 to 4.0 inclusive! Changing the 4 in the code to a 5 can give 4.1 and higher as well however, and that is no good.

My question is, what would be a more efficient way to code this? I apologize if there is a pretty straight forward answer/if this seems simple, but I am pretty new to coding and c++. Thank you!

J.Einhorn
  • 51
  • 6

1 Answers1

1

If it's just to find a gpa to one decimal place, you can find an int between 0 and 41 then divide by 10 to get a decimal. For example:

double rand2 = (double)(rand()%41)/10;

rand()%41 will generate a number that is between 0 and 40 inclusive. Then we cast it as a double and divide by 10. So if the generated number is 34, we get 3.4 as a double.

To use other double as the range, you would just multiply them by the number of decimal places you want following the number, then also divide by that number

//Range== 0,34 with 3 decimal places    
double rand2 = (double)(rand()%35000)/1000;
b13rg
  • 480
  • 6
  • 15
  • this is definitely the easiest way for me to follow, I should've thought more about the actual math of it rather than try to have perfect code. Thank you very much!! – J.Einhorn Jul 19 '17 at 22:25