Given the total number, determine how many times the value will go into it.

Problem:

The field can have 53 elements. If a person has 56 items, 2 boxes will be required to store them. Box 1 will contain 53 elements, and field 2 will have 3.

As I can repeat above, where 53 is a constant, immutable value and 56 is a variable for each field:

Math.Ceiling(Convert.ToDecimal(intFeet / 53))

what I still have:

int TotalItems = 56; 
int Boxes = Math.Ceiling(Convert.ToDecimal(intFeet / 53));  

for (int i = 0; i < Boxes; i++)
{  
    int itemsincurrentbox=??  
}  
+5
source share
6 answers

If the integers capacityand numItemsis your drawer capacity (53 in the example) and the total number of items you have, use the following two calculations:

int numBoxes = numItems / capacity;
int remainder = numItems % capacity;

(numBoxes) (remainder), , 0.

: , .NET Math.DivRem.

int remainder;
int numBoxes = Math.DivRem( numItems, capacity, out remainder );

.

+16

, :

int itemsPerBox = 53;
int totalItems = 56;
int remainder = 0;
int boxes = Math.DivRem(totalItems, itemsPerBox, out remainder);
for(int i = 0; i <= boxes; i++){
    int itemsincurrentbox = i == boxes ? remainder : itemsPerBox;
}
+6

, , , 53 , intFeet% 53 (intFeet mod 53 intFeet 53).

, ;

int totalItems = 56;
int boxes = Math.Ceiling(Convert.ToDecimal(totalItems / 53)) + 1;
for(int i=0; i< boxes;i++)
{
   int numberInBoxes = i != boxes -1 ? 53 : totalItems % 53;
}
+1

?

x % y
+1

. :

int totalBoxes = Math.Ceiling(Convert.ToDecimal(intFeet / 53));

List<int> boxes = new List<int>();
for (int i=0; i< totalBoxes; i++)
{
  if (i == totalBoxes-1) 
      boxes.Add(intFeet % 53)
  else 
      boxes.Add(53);
}
+1

All but the last will have 53 elements. As for calculating the number of full boxes and the number of elements in the last field, find integer division and module.

-1
source

All Articles