samedi 16 juin 2018

How to loop random number to make result equal user input summary

i have some problem like this. user(A) enter 500000 to my application and then i want to generate 50 random 5 digit number and when summary 50 random number need to equal 500000, How to do like i tried already but it's not working this is my code

            int balane = 500000;
            int nums = 50;
            int max = balane / nums;
            Random rand = new Random();
            int newNum = 0;
            int[] ar = new int[nums];
            for (int i = 0; i < nums - 1; i++)
            {
                newNum = rand.Next(0, max);
                ar[i] = newNum;
                balane -= newNum;
                max = balane / (nums - i - 1);

                ar[nums - 1] = balane;
            }

            int check = 0;
            foreach (int x in ar)
            {
                check += x;
            }

the result that i tell you not working because in my array list i have negative & positive value but the result equal 500000.

enter image description here

How to solve this issue ? Thank you very much.




Aucun commentaire:

Enregistrer un commentaire