New to coding and C++.
I'm having some issues with sorting out a random double to be only one decimal point. I've given it a look online and, from what I can tell and understand, I've got everything correct. Obviously not, however. Specifically, it appears that I may be using 'round()' incorrectly because, even when I don't do all the other multiplication (etc) to it, it doesn't round the double.
double u;
srand(unsigned(time(NULL)));
for(int i = 0; i < 10; i++){
u = (double)rand()/(RAND_MAX+1) + (rand()%101); //Acquire random number, turn it into decimal and then add it to another number between 0-100.
u *= 10; //Shift numbers left to remove first decimal from round.
round(u); //Round to nearest whole number.
u /= 10; //Shift right to return the first decimal.
cout<<u<<" "<<flush;
}
This method seems terrible to me. Obviously it won't work up at the higher reaches of double (since *10 might overload it, or whatever it's called). If someone could:
A) Show me where I went wrong with this code or, alternatively, hint it.
B) Suggest a better, more efficient way of doing this. As I'm sure there definitely is one.
C) Ability to round to decimal points other than the 1st.
Thanks and much appreciated in advance!
Aucun commentaire:
Enregistrer un commentaire