2011-11-21 47 views
1

我有這樣的方法:隨機漂浮的數學方程?

- (float)randomFloatBetween:(float)num1 andLargerFloat:(float)num2 { 
return ((float)arc4random()/ARC4RANDOM_MAX) * num2-num1 + num1; 
} 

而且我很好奇,如果有可能的,而不是使用條件語句爲以下: 我想打一個隨機浮動對我的比賽是這樣的:

When the score is: 
Score 0-20: I want a float between 4.0-4.5 using the above method 
Score 21-40: I want a float between 3.0-3.5 using the above method 
Score 41-60: I want a float between 2.5-3.0 using the above method 
Score 61+: I want a float between 2.0-2.5 using the above method 

現在我知道我可以使用條件來做到這一點,但是有沒有什麼數學方程比做這個更容易?

謝謝!

EDIT1:

- (float)determineFloat { 
    if (score <= 60) 
    { 
     //Gets the tens place digit, asserting >= 0. 
     int f = fmax(floor((score - 1)/10), 0); 

     switch (f) 
     { 
      case 0: 
      case 1: 
      { 
       // return float between 4.0 and 4.5 
       [self randomFloatBetween:4.0 andLargerFloat:4.5]; 
      } 
      case 2: 
      case 3: 
      { 
       // return float between 3.0 and 3.5 
       [self randomFloatBetween:3 andLargerFloat:3.5]; 
      } 
      case 4: 
      case 5: 
      { 
       // return float between 2.5 and 3.0 
       [self randomFloatBetween:2.5 andLargerFloat:3]; 
      } 
      default: 
      { 
       return 0; 
      } 
     } 
    } 
    else 
    { 
     // return float between 2.0 and 2.5 
     [self randomFloatBetween:2.0 andLargerFloat:2.5]; 
    } 
    return; 
} 

怎麼樣了這個?你是否確定這是最有效的方法?

回答

2

可能不會,因爲關係不連續。當你有這種需求時,最好只使用條件語句或switch語句。您和任何閱讀或調試代碼的人都會準確知道該功能在做什麼。在這種情況下使用某種數學函數,這種情況極其複雜,最有可能會降低流程的速度。

可能性使用開關:

-(float)determineFloat:(float)score 
{ 
    if (score <= 60) 
    { 
     //Gets the tens place digit, asserting >= 0. 
     int f = (int)fmax(floor((score - 1)/10.0f), 0); 

     switch (f) 
     { 
      case 0: 
      case 1: 
      { 
       return [self randomFloatBetween:4.0 andLargerFloat:4.5]; 
      } 
      case 2: 
      case 3: 
      { 
       return [self randomFloatBetween:3.0 andLargerFloat:3.5]; 
      } 
      case 4: 
      case 5: 
      { 
       return [self randomFloatBetween:2.5 andLargerFloat:3.0]; 
      } 
      default: 
      { 
       return 0; 
      } 
     } 
    } 
    else 
    { 
     return [self randomFloatBetween:2.0 andLargerFloat:2.5]; 
    } 
} 

用法:

float myScore = 33; 
float randomFloat = [self determineFloat:myScore]; 

現在,randomFloat將在3和3.5之間的值。

+0

什麼是使用條件最有效的方法,我應該如果if - > else if-> else if等...? –

+0

你有最高分嗎? –

+0

不,我沒有最高分 –