可以說我有以下幾點:
enum Color {
RED, GREEN, BLUE
};
Color foo;
我希望能夠有什麼要做的是將foo隨機分配給一種顏色。令人生厭的方式是:
int r = rand() % 3;
if (r == 0)
{
foo = RED;
}
else if (r == 1)
{
foo = GREEN;
}
else
{
foo = BLUE;
}
我想知道是否有更乾淨的方式來做到這一點。我已經嘗試(並失敗)以下內容:
foo = rand() % 3; //Compiler doesn't like this because foo should be a Color not an int
foo = Color[rand() % 3] //I thought this was worth a shot. Clearly didn't work.
讓我知道如果你們知道任何更好的方式,不涉及3 if語句。謝謝。
嘗試富=的static_cast(蘭特()%3); ?? –
2012-06-06 08:36:53