#include
#include
#include
#include
using namespace std;
//在[s, e)区间上随机取n个数并存放到a[]中
void GetRandomNum(int *a, int n, int s, int e)
{
std::set set_a;
srand(time(NULL));
for (int i = e - n; i < e; i++)
{
int num = (rand() % i) + s;
if (set_a.find(num) == set_a.end())
set_a.insert(num);
else
set_a.insert(i);
}
i = 0;
std::set::iterator pos;
for (pos = set_a.begin(); pos != set_a.end(); pos++)
a[i++] = *pos;
}
int main()
{
const int NSUM = 20;
const int NCOUNT = 4;
printf(" 生成和为%d的%d个数 \n", NSUM, NCOUNT);
printf("--- by MoreWindows( http://blog.csdn.net/MoreWindows ) ---\n\n");
int a[NCOUNT];
GetRandNumberInRange(a, NCOUNT - 1, 0, NSUM);
sort(a, a + NCOUNT - 1);
a[NCOUNT - 1] = NSUM;
printf(" 已经生成和为%d的%d个数: \n", NSUM, NCOUNT);
printf("%d ", a[0]);
for (int i = 1; i < NCOUNT; i++)
printf("%d ", a[i] - a[i - 1]);
putchar('\n');
return 0;
}