简体   繁体   中英

Rounding up and down a number C++

I'm trying to allow my program to round a number up and down respectively.

For example, if the number is 3.6 , my program is suppose to round up the nearest number which is 4 and if the number is 3.4 , it will be rounded down to 3.

I tried using the ceil library to get the average of 3 items.

results = ceil((marks1 + marks2 + marks3)/3)

However, the ceil only rounds the number down but does not roll the number up.

There's 1 algorithm i stumbled upon

var roundedVal = Math.round(origVal*20)/20;

but i still can't figure a formula for some problem.

std::ceil 

rounds up to the nearest integer

std::floor 

rounds down to the nearest integer

std::round 

performs the behavior you expect

please give a use case with numbers if this does not provide you with what you need!

The function you need is called round , believe it or not.

ceil rounds UP, btw. That is, to the closest larger integer. floor rounds down.

You don't need a function to round in C or C++. You can just use a simple trick. Add 0.5 and then cast to an integer. That's probably all round does anyway.

double d = 3.1415;
double d2 = 4.7;
int i1 = (int)(d + 0.5);
int i2 = (int)(d2 + 0.5);

i1 is 3, and i2 is 5. You can verify it yourself.

std::round may be the one you're looking for. However, bear in mind that it returns a float. You may want to try lround or llround to get a result in long or long long (C++ 11).

http://en.cppreference.com/w/cpp/numeric/math/round

In c++, by including cmath library we can use use various functions which rounds off the value both up or down.

std::trunc

This simply truncates the decimal part, thas is, the digits after the decimal point no matter what the decimal is.

std::ceil

This is used to round up to the closest integer value.

std::floor

This is used to round down to the closest integer value.

std::round

This will round to the nearest integer value whichever is the closest, that is, it can be round up or round down.

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