简体   繁体   中英

C# How to divide the number by equal constant?

Lets say i have a number that i need to split in array of 40, and also keep the leftover. For example:

int Num = 140;
Wanted: 40, 40, 40, 20

int Num = 75;
Wanted: 40, 35

What is the most elegant way to achieve this?

Thanks!

Hint: use modulus and division.

140 / 40 -> 3
140 % 40 -> 20

So, you would take the number divided by 40, and have that many 40 s in your array. Then append the number mod 40 to your array.

Pseudocode:

int[] result = new int[number / 140] + 1
fill up the array with (number / 140) 40's with a for loop
set the last element to number % 140

Try this function

List<int> split(int num, int splitBy)
{
    List<int> r = new List<int>();
    int v = Convert.ToInt32(num / splitBy);
    r.AddRange(Enumerable.Repeat(splitBy, v).ToArray());
    var remaining = num % splitBy;
    if (remaining != 0)
        r.Add(remaining);
    return r;
}

Use the % Operator , it will find your "Remainder". I will show you your 75 example, but because this looks a lot like homework I will leave it to you to figure out the 140 version.

int num = 75;

//numberOfEvens contains 1
int numberOfEvens = num / 40;
//remainder contains 35;
int remainder = num % 40;

Try this code. It should do what you want. But try to understand it of course otherwise it's no use.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] r1 = Split(140, 30);
            Print(r1);

            int[] r2 = Split(140, 40);
            Print(r2);

            int[] r3 = Split(75, 40);
            Print(r3);
        }

        public static void Print(int[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i] + " ");
            }
            Console.WriteLine();
        }

        public static int[] Split(int N, int val)
        {
            List<int> lst = new List<int>();
            int M = N;
            int v = 0;
            while (M > 0)
            {
                v = M > val ? val : M;
                lst.Add(v);
                M -= v;
            }
            return lst.ToArray();
        }
    }
}

My extension-method using LINQ:

public static class NumSplit
{
    public static int[] NumSplit(this int iNum, int div)
    {
        var CountInts = Enumerable.Repeat(div, iNum / div);
        var leftover = iNum % div;

        return leftover > 0 ? CountInts.Concat(new int[] { leftover }).ToArray() : CountInts.ToArray();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM