Evenly divide in c#

前端 未结 6 1717
梦谈多话
梦谈多话 2020-12-10 18:23

In c# how do I evenly divide 100 into 7?

So the result would be

  1. 16
  2. 14
  3. 14
  4. 14
  5. 14
  6. 14
  7. 14
6条回答
  •  有刺的猬
    2020-12-10 19:02

    Not sure why you are working with doubles but wanting integer division semantics.

        double input = 100;
        const int Buckets = 7;
        double[] vals = new double[Buckets];
        for (int i = 0; i < vals.Length; i++)
        {
            vals[i] = Math.Floor(input / Buckets);
        }
        double remainder = input % Buckets;
        // give all of the remainder to the first value
        vals[0] += remainder;
    

    example for ints with more flexibility,

        int input = 100;
        const int Buckets = 7;
        int [] vals = new int[Buckets];
        for (int i = 0; i < vals.Length; i++)
        {
            vals[i] = input / Buckets;
        }
        int remainder = input % Buckets;
        // give all of the remainder to the first value
        vals[0] += remainder;
    
        // If instead  you wanted to distribute the remainder evenly, 
        // priority to first
        for (int r = 0; r < remainder;r++)
        {
            vals[r % Buckets] += 1;
        }
    

    It is worth pointing out that the double example may not be numerically stable in that certain input values and bucket sizes could result in leaking fractional values.

提交回复
热议问题