Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a random number from 0 to 1700 in a string?

Tags:

c++

currently I'm working with

double fRand(double fMin, double fMax)
{
    double f = (double)rand() / RAND_MAX;
    return fMin + f * (fMax - fMin);
}

double RangeFinder::getRange(void) {
  return fRand(0, 1700);
};


char range[12];
double r = rangeFinder.getRange();
snprintf(range, 11, "range: %d", r);

But it isn't giving me between 0,1700 its giving me between -99,999 ( I think ). I have a feeling the msb is interpretting the thousands place as negative.

What's the fix?


Edit

fixed version

double fRand(double fMin, double fMax)
{
    double f = (double)rand() / RAND_MAX;
    return fMin + f * (fMax - fMin);
}

double RangeFinder::getRange(void) {
  return fRand(0, 1700);
};



char range[22];
int r = rangeFinder.getRange();
snprintf(range, 22, "range: %i    ", r);
LCDString(range);

the 2nd arg to snprintf was 11.. too short. there weren't white characters after the number to clear out previous values, and the double r needed to be cast int r.

like image 862
dansch Avatar asked Dec 04 '25 16:12

dansch


1 Answers

A possible problem is that the "%d" is used for integers. In order to print float/doubles you should use "%f"(floats) or "%lf"(doubles or long float).

like image 187
Simon Soriano Avatar answered Dec 07 '25 21:12

Simon Soriano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!