Home > Back-end >  How to generate C n random number makes them close to 1
How to generate C n random number makes them close to 1

Time:10-02

C language generates random number n, the random number range of 1 to 1, then the n input values for oneself, make random number close to 1, inquire,

CodePudding user response:

Random number reserved 2 decimal places

CodePudding user response:

Directly generated is not very good, can generate random Numbers are added to 0 n - 1, then the last number of the fixed to 1,

CodePudding user response:

For example
First to take a random number, base sum each generate a random number, then the base sum minus the random number to generate a random number, has been filled with n - 1, the last one with the remaining sum,
For example
int n;
The scanf (" % d ", & amp; N);
Double * d=(double *) malloc (sizeof (double) * n);
Srand (time (NULL));
Int s=100, t=0;
for (int i=0; IWhile (1) {
T=rand () % (2 + 1) * s - s;//generated [-s, s] random number
If (s - t<=100) break;
}
[I]=100.0 t/d;//[1, 1] is generated random number
S -=t;//modify after each generating random Numbers sum
}
Double [n - 1]=s/100.0;//the last

CodePudding user response:

While (1) {
T=rand () % (2 + 1) * s - s;//generated [-s, s] random number
If (s - t<=100) break;
}
To ensure the results less than or equal to 100 s - t
The previous random number range hands more convenient
Also can remove the cycle
  • Related