Tuesday, 15 July 2014

c# - Using switch statement for ranges -



c# - Using switch statement for ranges -

i'm trying map wind speed (measured in meters per second) appropriate label, taken http://www.windfinder.com/wind/windspeed.htm. this, i'd utilize switch statements, i'm not sure how in c#.

in actionscript, possible using switch blocks, i've seen in clang.

// actionscript 3 switch(true) { case: mps >= 0 && <= 0.2 homecoming windspeedlabel.calm; break; ... case else: windspeedlabel.shithittingthefan; } // clang switch(mps) { case 0 ... 0.2: homecoming windspeedlabel.calm; ...

i'm aware it's possible using if/else statements, 13 different ranges, appreciate more readable solution.

switch statements according msdn,

each case label specifies constant value. switch statement transfers command switch section case label matches value of switch expression

thus, cannot specify range, , when working doubles, case of rounding , slight inaccuracies create exact matches poor selection @ best.

update: if want readability, best can offer single lines , perchance hand alignment

if(mps >= 0 && <= 0.2) homecoming windspeedlabel.calm; else if(mps <= 0.4) homecoming windspeedlabel.gusty; ... else homecoming windspeelabel.hurricaneforce5;

note above code not utilize minimum range after first statement - prevent slight rounding errors causing given wind speed fall through. because doubles on hardware levels store using binary , occaisionally have little grade of error, resulting in 0.2 coming runtime 0.200000000000000001 or 0.1999999999999999 - while rare, can cause behavior inconsistent our human-perceived notion of numbers, , makes double testing imply previous statement risky.

if absolutely must have switch statement, render wind speed string or round it.

switch((int)(mps * 10)) { case 0: case 1: case 2: homecoming windspeedlabel.calm; break; }

c# .net mapping switch-statement

No comments:

Post a Comment