我如何将浮点数舍入到int?

时间:2015-12-07 00:40:03

标签: c math

说我有:

55.3 and want 55
55.6 and want 56
81.1 and want 81
etc.

我一直在尝试使用round()函数,但它似乎一直给我所有小数位的最高值。

3 个答案:

答案 0 :(得分:3)

OP尚未发布失败的代码。某些OP编码错误。

在转换为round()之前,使用double 正确的方法来舍入int。当然它必须在范围内。

#include <math.h>
#include <assert.h>

int round_to_int(double x) {
  x = round(x);
  assert(x >= INT_MIN);
  assert(x < (INT_MAX/2 + 1)*2.0);
  return (int) x;
}

有关assert()的详细信息,请参阅How to test for lossless double / integer conversion?

为什么不使用(int)(x + 0.5);

1)否定数字失败。

2)由于double可能会小于0.5x + 0.5可能会失败,因为1.0可能会转到int

3)当double的精度超过x+0.5时,最低有效位为0.5或1.0的值,#~~~~~DOWNLOAD~~~~~# elif nextCommand.find("DL") == 0 or nextCommand.find("dl") == 0: sendPath = nextCommand[3:] print "Attempting download using filepath as: " , sendPath fileInfo = s.recv(1024) print "Download Request Acknowledged from server" # , fileInfo if fileInfo.find("Error") == 0: print "Error Opening File" else: if fileInfo: fL = fileInfo.split("|") dlPath = fL[0] fileSize = fL[1] f = open(dlPath, 'wb+') #Download Target Path print "Saving file as:" , f.name print "Recieved File Size as:" , fileSize fSize = int(fileSize) fileContent = s.recv(fSize) f.write(fileContent) print "Download Complete" f.close() 可能舍入到下一个整数

4)简单,没有范围检查。

答案 1 :(得分:2)

过去我们常说int the_int = (int)(some_double + 0.5);(显然要注意你是否也在处理负值)。

答案 2 :(得分:1)

将幅度增加一半并截断:

int round_up_or_down(double x)
{
    return x > 0 ? x + 0.5 : x - 0.5;
}

这统一分配实际间隔:

  • ...
  • [-1.5, -0.5) => -1
  • [-0.5, +0.5) => 0
  • [+0.5, +1.5) -> +1
  • ...
相关问题