c++研发笔试题目!求好的解法
在游戏中,角色有5个属性分别是A、B、C、D、E 使这5个属性随机的变化,并且每个属性值保持在10~35之间,总和为100不变!要求效率尽可能的高!给出算法来!有没有哪位仁兄知道好的方法的?

重剑无锋,大巧不工
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand( (unsigned)time(NULL) ); int sum = 50; for( int i=0; i<4; ++i ) { int v = ( sum!=0 ? rand()%min(26,sum) : 0 ) + 10; sum -= v-10; cout << char('A'+i) << " = " << v << endl; } int E = sum + 10; cout << "E = " << E << endl; return 0; }
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { srand( (unsigned)time(NULL) ); int V[5] = { rand()%26, rand()%26, rand()%26, rand()%26, rand()%26 }; // 可以优化成只要调要两次rand(),但不想麻烦了 int S = V[0] + V[1] + V[2] + V[3] + V[4]; if( S == 0 ) { V[0] = V[1] = V[2] = V[3] = V[4] = 20; } else { // 将各项等比率扩张或缩小,使之等于100 V[0] = V[0] * 50/S + 10; V[1] = V[1] * 50/S + 10; V[2] = V[2] * 50/S + 10; V[3] = V[3] * 50/S + 10; V[4] = V[4] * 50/S + 10; // 但有可能总和还是不等于100,因此将剩余的几个数随机分掉 S = 100 - (V[0] + V[1] + V[2] + V[3] + V[4]); if( S != 0 ) { int r = rand(); // 因为S一定是大于0小于5的,5*5*5*5<RAND_MAX,所以一个rand()就够了 for( int i=0; i<S; ++i ) { ++V[r%5]; r /= 5; } } } printf( "A = %d\n", V[0] ); printf( "B = %d\n", V[1] ); printf( "C = %d\n", V[2] ); printf( "D = %d\n", V[3] ); printf( "E = %d\n", V[4] ); return 0; }