Given an input value returns values like 1050, 1150, 1250, 1350, 1450,
I'm developing a C++ algorithm that, given a float number as input, it returns its closest value to number ending in 50. Sorry, i don't know how to explain it better. With examples I mean, I need these numbers: 50, 150, 250, 350, 450, 550, etc.
In other words, if the input value is between, i.e., [1050, 1100)
, it will return 1050, but if the value is between [1100, 1150]
, it will return 1150.
So, this is my algorithm with only works when input values are equal or greater than 1000.0:
- Divide input value by 100.0.
- Take fraction part
- If faction part is greater or equal to 0.0 and less than 0.5 then add one to integer part.
- Multiply integer part by 100.
- To the result add 50.
When the input is 701.272 it returns 850.0, but it should return 750.0.
Maybe the problem is divide and multiple by 100 if the input number is less than 1000.
How can I fix this algorithm?
Answers
You can simplify the algorithm by first rounding the input value to the nearest multiple of 100, and then adding 50 to get the closest value ending in 50. Here's how you can do it:
#include <iostream>
#include <cmath>
float closestTo50(float num) {
// Round the input value to the nearest multiple of 100
float rounded = round(num / 100.0) * 100.0;
// Add 50 to get the closest value ending in 50
float closest = rounded + 50.0;
return closest;
}
int main() {
// Example usage
float input = 701.272;
float result = closestTo50(input);
std::cout << "Closest value to " << input << " ending in 50: " << result << std::endl;
return 0;
}
This algorithm will work correctly for input values less than 1000.0 as well. It first rounds the input value to the nearest multiple of 100, and then adds 50 to get the closest value ending in 50. So, for the input value of 701.272, it will correctly return 750.0.