四舍五入C ++ [英] Rounding up and down a number C++

查看:153
本文介绍了四舍五入C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图允许我的程序分别将数字四舍五入。

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

例如,如果数字为 3.6 ,则我的程序假设四舍五入到最接近的数字4并且如果数字为 3.4 ,则将其四舍五入为3。

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.

我尝试使用 ceil 库以获取3个项目的平均值。

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

结果= ceil((marks1 + marks2 + mark3)/ 3)

但是, ceil 仅将数字四舍五入,但是

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

我偶然发现了1种算法

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

但我仍然无法解决某些问题的公式。

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

推荐答案

std::ceil 

舍入到最接近的整数

std::floor 

向下舍入到最接近的整数

rounds down to the nearest integer

std::round 

执行您期望的行为

如果没有为您提供所需的用例,请提供带有数字的用例!

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

这篇关于四舍五入C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆