Can someone help me understand what the purpose of these steps are? It seem like the code computes a number as an integer while also multiplying it by 10.5 and then converts it back to a float and divides it by 10.0.
My questions are:
1. why convert it to an int at all?
2. why multiply by 10.5? if you we just divide by 10.0? won't that throw off the math?
3. why calculate 10.5 as "10.0 + 0.5"? why not just "10.5"?
// Compute miles for each distance on the map
miles = float(int(distance1 * scale * 10.0 + 0.5)) / 10.0;
outData << "For a measurement of " << distance1
<< " the first distance is " << miles
<< " mile(s) long." << endl;
totMiles = totMiles + miles;
ANSWER TO MY OWN QUESTION:
That's a way to round the number to the nearest 10th.
Try some examples:
let x = distance*scale
if x = 12.345
then
10x+.5 = 123.95
int( 123.95 ) = 123
123/10 = 12.3
thus the number is correctly rounded to the nearest 10th.
I had some trouble with the logic on this problem too but your comments were very helpful.
ReplyDelete