求帮助,随机产生和为 100 的 10 个 0-30 的随机数,和为 100 不会怎么实现,
求帮助,随机产生和为100的10个0-30的随机数,和为100不会怎么实现,
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { int a[10] ; int i, temp ; int sum = 100 ; //和初始化为100 srand ( (unsigned)time(0) ); /* **因为和固定为100,所以只需要随机生成9个数,100减9个数之和就是第十个数 */ for ( i = 0; i < 9; i++) { temp = rand() % 31 ; /* **每生成一个数temp,就用sum-temp检查生成的数字之和是否超过了100 */ if ( sum - temp >= 0 ) { a[i] = temp ; sum -= temp ; } else { i-- ; } } a[9] = sum ; for ( i = 0; i < 10; i++ ) { printf("%02d ",a[i]); } printf ( "\n" ) ; system("pause"); return 0; }
#include <stdio.h> #include <stdlib.h> #include <time.h> int a[10]; int i, j, k, sum = 0; void print(int *b); int main(void) { srand((unsigned int)time(NULL)); L:for (i = 0; i < 10; i++) { a[i] = 1 + (int)(30.0 * rand() / (RAND_MAX + 1.0)); do { i++; a[i] = 1 + (int)(30.0 * rand() / (RAND_MAX + 1.0)); for (j = 0; j < i;) { if (a[i] != a[j]) { j++; } else { a[i] = 1 + (int)(30.0 * rand() / (RAND_MAX + 1.0)); i--; continue; } } //printf("%d %d\n", a[i-1], a[i]); } while (i < 9); for (k = 0; k < 10; k++) { sum += a[k]; } if (sum != 100) { sum = 0; goto L; } } print(a); printf("\n"); return 0; } void print(int *b) { int t, x, y; for (x = 0; x < 10; x++) { for (y = 0; y < (9 - x); y++) { if (b[y] > b[y + 1]) { t = b[y]; b[y] = b[y + 1]; b[y + 1] = t; } } } for (x = 0; x < 10; x++) { printf("%02d ", b[x]); } }