在C ++中取整 [英] Rounding up in C++

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

问题描述

您好,我想知道是否有人可以告诉我如何使用C ++进行总结.
基本上是制作油漆估算器,例如

1升油漆覆盖8平方米

浮动天花板= 18.7;

上限= 18.7/8;

所以现在上限为2.3375

但是您不能购买需要3的价值2.3375升的油漆,所以我想知道如何编程,以便可以对2.3375进行四舍五入,或者任何数据输入可能等于下一个整数.

Hi, was wondering if anyone can inform me how to round up in C++.
Basically making a paint estimator and for example

1 ltr of paint covers 8 square meters

float ceiling = 18.7;

ceiling = 18.7/8;

so now ceiling will be 2.3375

but you cant buy 2.3375 litres worth of paint you need 3, so I wana know how I could program it so that I can round 2.3375 or whatever the data input might be up to the next whole number.

推荐答案

您似乎想知道在特定数量中有多少个特定大小的商品.我很想尝试类似的东西:

It looks like you want to know how many lots of a certain size are in a particular number. I''d be tempted to try something like:

double round_up_to_nearest_lot( double quantity, double lot_size )
{
    unsigned lots = unsigned( quantity / lot_size );
    if( (lots * lot_size) < quantity ) lots++;
    return lot_size * lots;
}



此处的关键是对需要满足特定数量的最低起订数量进行低阶估计,然后检查是否足够.如果不能将数字加一,再使用那么多.

只是重新阅读您的问题..您实际上想要查找批号(即油漆罐),因此您可以执行以下操作:



The key here to work out a low order estimate of how many lots minimum you need to cover a particular quantity then check that it''s enough. If not bump the number by one and use that many lots.

Just re-reading your problem a bit.. you actually want to find the number of lots (i.e. cans of paint), so you could do something like:

unsigned number_of_lots_in_quantity( double quantity, double lot_size )
{
    unsigned lots = unsigned( quantity / lot_size );
    if( (lots * lot_size) < quantity ) lots++;
    return lots;
}



您可以按照以下方式来称呼它:



and you''d call it along the lines of:

unsigned cans_of_paint_required( number_of_lots_in_quantity( area_to_cover, size_of_can ) );



无论如何,希望这是一种接近您想要的东西,并且他们以我所追求的方式是可以理解的.请注意,如果手数大于系统上整数的大小,则这两个函数将都是垃圾.

干杯,



Anyway, hope that''s something approaching what you want and they way I''ve gone about it is understandable. Note that both those functions are going to be rubbish if the number of lots is greater than the size of an integer on your system.

Cheers,

Ash


在天花板上添加0.9999并将其四舍五入.
Add 0.9999 to ceiling and round that down.


将其设置为int并添加+ 0.5f
solved it by making it an int and adding +0.5f


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

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