Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 随机颜色发生器_C++_Random_Colors_Sdl - Fatal编程技术网

C++ 随机颜色发生器

C++ 随机颜色发生器,c++,random,colors,sdl,C++,Random,Colors,Sdl,我的朋友给了我一些SDL程序的代码,我只知道它会产生随机颜色,但我不知道它是如何工作的,下面是代码 int unsigned temp = 10101;//seed for(int y = 0;y < times;y++){ temp = temp*(y+y+1); temp = (temp^(0xffffff))>>2; //printf("%x\n",temp); SDL_FillRect(sprit

我的朋友给了我一些SDL程序的代码,我只知道它会产生随机颜色,但我不知道它是如何工作的,下面是代码

 int unsigned temp = 10101;//seed
    for(int y = 0;y < times;y++){
        temp = temp*(y+y+1);
        temp = (temp^(0xffffff))>>2;
        //printf("%x\n",temp);
        SDL_FillRect(sprite[y],NULL,temp);
        SDL_BlitSurface(sprite[y],&paste[y],rScreen(),NULL);
        }
int无符号温度=10101//种子
对于(int y=0;y>2;
//printf(“%x\n”,temp);
SDL_FillRect(精灵[y],空,温度);
SDL_BlitSurface(精灵[y],&paste[y],rsScreen(),NULL);
}

我的问题是,这段代码是如何工作的,它是如何产生一种随机的颜色的?神奇之处在于这四行:

unsigned int temp = 10101; // seed - this seeds the random number generator

temp = temp * (y + y + 1); // this performs a multiplication with the number itself and y
// which is incremented upon each loop cycle
temp = (temp ^ 0xffffff) >> 2; // this reduces the generated random number
// in order it to be less than to 2 ^ 24
SDL_FillRect(sprite[y], NULL, temp); // and this fills the rectangle using `temp` as the color
// perhaps it interprets `temp` as an RGB 3-byte color value
你的朋友正在用他发明的一些业余PRNG创建一个范围从0x000000到0xFFFFFF的“随机RGB值”

我将用注释解释代码:

这就是所谓的“种子”。将生成伪随机值序列的初始值

 int unsigned temp = 10101; //seed 
然后我们得到了for循环:

 for(int y = 0;y < times;y++)
 {
    temp = temp*(y+y+1);
    temp = (temp^(0xffffff))>>2;

“一些业余的PRNG。”-是的,相当业余,而且他的编码风格特别差。为什么“他错误地使用了按位异或而不是按位和&”,代码是有效的,所以它不正确吗?@Laggy:说到PRNG,很难说“它有效”或“它不起作用”。我们应该谈谈生产价值的统计分布。一个好的PRNG应该近似于伪随机预言(一个能给出完美随机值的数学模型)。乍一看,很明显,提供的代码不是一个好的PRNG。按位AND将强制范围从0x000000到0xFFFF;相反,XOR^只是翻转temp的位,让它自由地超过0xFFFFFF限制。也许除以2只是为了将值保持在范围内。为什么不使用一些标准的PRNG,比如rand()之类的呢?你不需要高质量的随机性(你不是为了加密目的而编码),所以rand()应该能以近乎零的努力完成一项伟大的工作。它做得很好,但我只想知道它是如何工作的,现在我知道了,谢谢anwsers
    //printf("%x\n",temp);
    SDL_FillRect(sprite[y],NULL,temp);
    SDL_BlitSurface(sprite[y],&paste[y],rScreen(),NULL);
 }