language agnostic - What is the cleanest way to round a value to nearest 45 degrees? -
i have same question question here.
the user asked:
i wrote return nearest 45 degree angle. 0, 45, 90, 135...
it feels there must better way of doing though. working fine looks messy.
public function nearestdeg(degs:int):int { if (degs >= 0 && degs <= 45) { if (degs <= 23) { return 0; }else { return 45; } } if (degs > 45 && degs <= 90) { if (degs <= 68) { return 45; }else { return 90; } } if (degs > 90 && degs <= 135) { if (degs <= 113) { return 90; }else { return 135; } } if (degs > 135 && degs <= 180) { if (degs <= 158) { return 135; }else { return 180; } } if (degs > 180 && degs <= 225) { if (degs <= 203) { return 180; }else { return 225; } } if (degs > 225 && degs <= 270) { if (degs <= 248) { return 225; }else { return 270; } } if (degs > 270 && degs <= 315) { if (degs <= 293) { return 270; }else { return 315; } } if (degs > 315 && degs <= 360) { if (degs <= 338) { return 315; }else { return 360; } } return 0; }
what cleanest way round value nearest 45 degrees?
i'd divide value 45°, round, , multiply 45°. pseudocode:
deg = round(deg / 45) * 45;
assumption: /
operator returns floating-point representation , not perform integer division. if specific language not treat should handled explicitly (e.g., divide 45.0
instead of 45
).
Comments
Post a Comment