这就是数学的魅力
^_^
你可以看看这个
http://blog.csdn.net/u010141928/article/details/71439570
http://blog.csdn.net/iamhalfmoon/article/details/6010710
另外,再给出我自己写的代码#include <iostream>
#include <iomanip>
int GetResult(int min, int max, int r)
{
return (max - min + 1) * r / (RAND_MAX + 1) + min;
}
int GetMin(int min, int max, int i)
{
for(int r = 0; r <= RAND_MAX; ++r)
{
if(GetResult(min, max, r) == i)
return r;
}
return -1;
}
int GetMax(int min, int max, int i)
{
int r = 0;
for(; r <= RAND_MAX; ++r)
{
if(GetResult(min, max, r) == i)
break;
}
for(; r <= RAND_MAX; ++r)
{
if(GetResult(min, max, r) != i)
return r - 1;
}
return -1;
}
int main(void)
{
int min = 0, max = 10;
std::cout << std::setfill('0') << std::setiosflags(std::ios::uppercase);
for(int i = min; i <= max; ++i)
{
std::cout << std::dec << i;
std::cout << "\t";
std::cout << std::hex
<< "0x" << std::setw(8) << GetMin(min, max, i)
<< " - "
<< "0x" << std::setw(8) << GetMax(min, max, i)
<< std::endl;
}
return 0;
}
0 0x00000000 - 0x00000BA2
1 0x00000BA3 - 0x00001745
2 0x00001746 - 0x000022E8
3 0x000022E9 - 0x00002E8B
4 0x00002E8C - 0x00003A2E
5 0x00003A2F - 0x000045D1
6 0x000045D2 - 0x00005174
7 0x00005175 - 0x00005D17
8 0x00005D18 - 0x000068BA
9 0x000068BB - 0x0000745D
10 0x0000745E - 0xFFFFFFFF
请按任意键继续. . .
-5 0x00000000 - 0x000007FF
-4 0x00000800 - 0x00000FFF
-3 0x00001000 - 0x000017FF
-2 0x00001800 - 0x00001FFF
-1 0x00002000 - 0x000027FF
0 0x00002800 - 0x00002FFF
1 0x00003000 - 0x000037FF
2 0x00003800 - 0x00003FFF
3 0x00004000 - 0x000047FF
4 0x00004800 - 0x00004FFF
5 0x00005000 - 0x000057FF
6 0x00005800 - 0x00005FFF
7 0x00006000 - 0x000067FF
8 0x00006800 - 0x00006FFF
9 0x00007000 - 0x000077FF
10 0x00007800 - 0xFFFFFFFF
请按任意键继续. . .
其实就是一个范围的分配 |