I generate (float) random numbers between -99 and 99, and would like to put each number into the corresponding box. For example, if the number is -96., then it should go into the second box. if the number is 4.9, then it goes into the 52. box.
What is the best way to do this ? Can I do it with a simple array, struct,.... ?
It'll depend on what you want to do with the program and whether it should be portable or just to try something or what?!
In your special case above and if I understood it correctly you want to count the matches in each "box" or what. After your example your boxes two and 52 would show 1 and the rest zero?! Is this correct? Or do you want to store actual numbers?
Ok next question: do all those boxes have always the same spacing and same size or does it vary?
If you can answer yes I would do some mystic math:
number -= offset (offset = lower border = -99 -> therefore making smallest number possible 0)
number /= spacing (=2 -> calculating for boxes of size 1)
now all you need is floor which is a function of math.h (cutting off all decimal digits)
what it does so far:
1 2 3 4 5 6 7
bool boxes[100] = false;
float number = -98.1;
number -= -99; //-> number = 0.9 now
number /= 2; //-> number = 0.45 now
floor( number ); //-> number = 0; (should go to box zero! , which would be your box one but if you use arrays zero is the first index)
boxes[(int)number] = true; //set our box *number* to true
an even cooler way doing would be using "vector" class with boolean types -> it uses less memory and has some cool functions...it comes with vector.h
Oh if your answer would be "no" then you need to store lower and upper bounds of each box as well and cycle through all of them each step till you find the matching one e.g.
if( box[i].lowerbound <= number and box[i].upperbound > number ) box[i].value = true;