【问题标题】:Using Double in Switch Statement在 Switch 语句中使用 Double
【发布时间】:2012-09-13 02:40:38
【问题描述】:

以下所有值都是双精度值,但 switch 需要一个整数值。反正有这个吗?

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;

【问题讨论】:

  • 比较浮点的相等性从来都不是一个好主意,所以 switch 在浮点上是一个非常糟糕的主意。
  • case 值必须是编译时常量。

标签: objective-c ios switch-statement


【解决方案1】:

您可能最好只使用 if else 并测试范围,但您可以对您的 FivePercentValue 执行一些数学运算,然后将其转换为整数,以便不同的整数代表不同的范围,例如

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;
    ....
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多