Home >Backend Development >PHP Tutorial >PHP implements red envelope sending program
Let’s analyze the rules first. Set the total amount to 10 yuan, and N people will receive it randomly: N=1 first Then the red envelope amount = X yuan; N=2 second To ensure that the second red envelope can be issued normally, the amount of the first red envelope = a random number between 0.01 and 9.99. The second red envelope = 10-the amount of the first red envelope; N=3 third Red envelope 1 = a random number between 0.01 and 9.99 Red envelope 2 = a random number from 0.01 to (10-red envelope 1-0.01) Red envelope 3=10-Red envelope 1-Red envelope 2 … So we get a rule. When allocating the current red envelope amount, first reserve the minimum amount required for the remaining red and white, and then take a random number between 0.01 and the total amount - the reserved amount. The random number obtained is the amount of the current red envelope distribution. . In actual application, the program first allocates the amount of red envelopes. That is, when issuing red envelopes, the number of red envelopes and the amount of each red envelope are allocated. Then when the user comes to grab the red envelope, we can randomly return a red envelope to the user. Red envelope distribution code:
Running the above code will output the following results: The first red envelope, the amount is 2.08 yuan, the balance is 17.92 yuan The second red envelope, the amount is 1.81 yuan, and the balance is 16.11 yuan The third red envelope, amount 0.15 yuan, balance 15.96 yuan The fourth red envelope, the amount is 1.61 yuan, and the balance is 14.35 yuan The fifth red envelope, the amount is 1.11 yuan, and the balance is 13.24 yuan The 6th red envelope, the amount is 1.51 yuan, the balance is 11.73 yuan The 7th red envelope, amount 1.21 yuan, balance 10.52 yuan The 8th red envelope, amount 2.58 yuan, balance 7.94 yuan The 9th red envelope, the amount is 5.4 yuan, the balance is 2.54 yuan The 10th red envelope, amount 2.54 yuan, balance 0 yuan Original text http://www.helloweba.com/view-blog-313.html |