Three numbers are random (must be 1 ~ 9), their and equal to a certain number (range is 14 ~ 19)

xiaoxiao2021-03-06  39

The algorithm needs to be noted that the generation of the second number is required to be specially processed. The following programs are tested under the VC . Net:

#include #include

/// randomly generate three numbers (must be 1 ~ 9), they are equal to a certain number (range is 14 ~ 19). // The first parameter is these three numbers and (ranges 14 ~ 19) // second parameters to output the generated random number // void getrandom (int sum, int * number {int TEMP;

SRAND (NULL);

// Generate a random number NUM [0] = 1 rand ()% 8;

/ / Then get the resulting range of the next number TEMP = Sum - Num [0];

IF (Temp == 18) {Num [1] = NUM ​​[2] = 9;} else if (Temp> 9) {// If Temp> 9, in order to ensure NUM [2] <= 9, you must let Num [ 1] Between TEMP-9 to 9. NUM [1] = (Temp - 9) rand ()% (18-TEMP);} else {// If Temp <9, in order to ensure NUM [2]> = 1, you must let Num [1] in 1 to TEMP-1 between. NUM [1] = 1 rand ()% (Temp - 1);

Num [2] = Temp - Num [1];

Void main (void) {Int Num [3] = {0, 0, 0};

Getrandom (14, NUM);

Printf ("1st Number:% D / N", NUM [0]); Printf ("2nd Number:% D / N", NUM [1]); Printf ("3rd Number:% D / N", NUM [ 2]);}

转载请注明原文地址:https://www.9cbs.com/read-66546.html

New Post(0)