问题
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.
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
回答1:
int fileSize = 257019;
int partSize = Math.ceil( ((double)fileSize) / 100);
int lastPacket = 257019 - (99 * partSize);
In this case:
int partSize = 2571;
int lastPacket = 257019 - 254529 = 2490 < 2571
The original problem with your code:
(int) Math.ceil(257019 / partSize) == 100
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.
回答2:
int partSize = totalSize / 100;
if ((totalSize % 100) != 0) {
partSize++;
}
来源:https://stackoverflow.com/questions/17954480/split-number-to-equal-parts-where-the-last-part-is-equal-or-lower-to-the-rest