Using Double in Switch Statement

喜你入骨 提交于 2020-01-04 04:16:32

问题


All of the values below are doubles, yet switch requires a integer value. Is there anyway around this?

switch(fivePercentValue){
case floor((5*fivePercentValue) / 100):
    fivePercent_.backgroundColor = [UIColor greenColor];
    fivePercentLabel_.textColor = [UIColor greenColor];
    break;
case ceil((5*fivePercentValue) / 100):
    fivePercent_.backgroundColor = [UIColor greenColor];
    fivePercentLabel_.textColor = [UIColor greenColor];
    break;
default:
    fivePercent_.backgroundColor = [UIColor redColor];
    fivePercentLabel_.textColor = [UIColor redColor];
    break;

回答1:


You are probable better of just using if else and testing for ranges but you can perform some maths on you fivePercentValue and then convert it to a integer so that different integers represent different ranges for example

switch( (int)(value*10.0) )
{
    case 0:        // this is 0.0 <= value < 0.1
        break;
    case 1:        // this is 0.1 <= value < 0.2
        break;
    case 2:        // this is 0.2 <= value < 0.3
        break;
    ....
}


来源:https://stackoverflow.com/questions/12398719/using-double-in-switch-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!