将数字拆分为相等的部分,其中最后一部分等于或低于其余部分 [英] Split number to equal parts where the last part is equal or lower to the rest

查看:85
本文介绍了将数字拆分为相等的部分,其中最后一部分等于或低于其余部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,希望将其拆分为100个.
文件大小为257019字节.
当在下面运行我的分割器代码时,我得到99个部分,大小为2545字节,最后100个部分为5064字节.

I have a file that I want to split into 100 pieces.
The file size is 257019 bytes.
When running my splitter code below I get 99 parts with a size of 2545 byte and the last 100'th part is 5064 byte.

我需要帮助找出如何使前99个部分的大小相同,而后100个部分的剩余字节数等于或小于2545.

I need help to figure out how to make the first 99 parts having the same size and the last 100'th part having the leftover bytes that is equal or lower then 2545.

int partSize;
for(partSize=1 ;partSize< 257019; partSize++){
   if((int) Math.ceil(257019 / partSize) == 100){
     break;
   }
}

int totalparts = (int) Math.ceil(257019 / partSize); // =100

推荐答案

int fileSize = 257019;
int partSize = Math.ceil( ((double)fileSize) / 100);
int lastPacket = 257019 - (99 * partSize);

在这种情况下:

int partSize = 2571;
int lastPacket = 257019 - 254529 = 2490 < 2571

您的代码的原始问题:

(int) Math.ceil(257019 / partSize) == 100

是在评估Math.ceil之前先评估257019 / partSize.如果将整数除以整数,结果将自动为整数.整数的默认行为是省略除十进制本身之外的所有内容,因此它将自动"Math.floor()".

is that 257019 / partSize is evaluated before Math.ceil is evaluated. If you divide an integer by an integer, the result is automatically an integer. The default behavior of an integer is to omit everything but the decimal itself, so it will automatically "Math.floor()" it.

这篇关于将数字拆分为相等的部分,其中最后一部分等于或低于其余部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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