简体   繁体   中英

Round down to the nearest multiple of five c++

I have a little problem with the round down.

I would round down the number to the nearest multiple of five.

Here some examples:

4 -> 0

67 -> 65

23 -> 20

44 -> 40 

59 -> 55

I tried in different ways, but I can't do it.

Is there some method to do it?

Assuming your number is stored in an integer format, you can use integer division for this:

int a = 44;
int r = (a/5) * 5; //will round down to 40

If you have variables of type int , you can employ the fact that dividing them with an other int will give you an integer, so that if you multiply again by that number, you get what you want.

So:

int a = 59;
std::cout << ((a / 5) * 5) << "\n";

would output 55.

If the values are not stored as integer, you can cast them before executing the division:

float a = 59;
std::cout << ((static_cast<int>(a) / 5) * 5) << "\n";

There is a method to do it, integer division:

int n{44};
int multiple_of_five = (n / 5) * 5;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM