當我嘗試將函數作爲參數傳遞給另一個函數時,我用C++遇到了這個奇怪的事情。這裏的問題是它的工作原理,但沒有給我預期的結果。 這裏是我的代碼(msvc2013):將函數作爲參數傳遞給C++時出現錯誤
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <iostream>
typedef unsigned int uint32_t;
typedef unsigned char uint8_t;
using namespace std;
#include "stdafx.h"
uint32_t random_color()
{
uint8_t r = rand() % 255;
uint8_t g = rand() % 255;
uint8_t b = rand() % 255;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
return rgb;
}
void print_rgb(uint32_t(*color_generator)() = &random_color)
{
std::cout << color_generator << std::endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
for (int i = 0; i < 5; i++)
{
srand(time(NULL));
print_rgb();
}
system("PAUSE");
return 0;
}
這段代碼的目的是比較複雜的,但是這是一個小例子。
問:雖然正如你看到的,有爲了是一個srand(time(NULL));
爲rand()
改變價值觀,它這麼想的!
這是有什麼理由嗎?我錯過了什麼嗎?
如果你需要隨機數字,不要使用'rand()'。問題在於,你使用相同的種子在循環內播種rng,並且兩次迭代之間的時間不會改變。在這個上有幾十個重複。 – user463035818
這不是呈現問題,但只調用'srand'一次。不要每次循環都調用它。 –
如果它沒有給出預期的結果,那麼它不起作用。 –