0

我有代码来比较 cellforrowAtIndexPath 中的浮点值或双精度值。我正在比较它并在评估比较值时将颜色设置为 tableView 单元格。但有时,当值不同时,它不会进入不等于条件。任何人都可以告诉我我可以用来比较两个的正确方法是什么浮点数或双精度值。不等于条件(!=)的日志有时不打印。

我的代码如下:---

double br_preVal=[[[prevDict valueForKey:@"bestbuyprice"] valueForKey:@"text"] doubleValue];
double br_nxtVal=[[[tempDic valueForKey:@"bestbuyprice"] valueForKey:@"text"] doubleValue];

double sr_preVal=[[[prevDict valueForKey:@"bestsellprice"] valueForKey:@"text"] doubleValue];
double sr_nxtVal=[[[tempDic valueForKey:@"bestsellprice"] valueForKey:@"text"] doubleValue];


if (br_nxtVal!=br_preVal) {

    NSLog(@"buy rate Not equal === and values %f,%f",br_preVal,br_nxtVal);

    if (br_nxtVal>br_preVal) {
        [mwCell.buyRate setBackgroundColor:t.socketHighbgColor];
        mwCell.buyRate.textColor=t.socketHighfgColor;

        [celllc replaceObjectAtIndex:indexPath.row withObject:t.socketHighbgColor];
    }else{
        [mwCell.buyRate setBackgroundColor:t.socketLowbgColor];
        mwCell.buyRate.textColor=t.socketLowfgColor;

        [celllc replaceObjectAtIndex:indexPath.row withObject:t.socketLowbgColor];
    }
}else{

    mwCell.buyRate.backgroundColor=[celllc objectAtIndex:indexPath.row];
    mwCell.buyRate.textColor=([[celllc objectAtIndex:indexPath.row] isEqual:t.socketLowbgColor])?t.socketLowfgColor:t.socketHighfgColor;
}

if (sr_nxtVal!=sr_preVal) {

    NSLog(@"sell rate Not equal === and values ==  %f,%f",sr_preVal,sr_nxtVal);

    if (sr_nxtVal>sr_preVal) {
        [mwCell.sellRate setBackgroundColor:t.socketHighbgColor];
        [mwCell.sellRate setTextColor:t.socketHighfgColor];

        [cellrc replaceObjectAtIndex:indexPath.row withObject:t.socketHighbgColor];
    }else{
        [mwCell.sellRate setBackgroundColor:t.socketLowbgColor];
        [mwCell.sellRate setTextColor:t.socketLowfgColor];

        [cellrc replaceObjectAtIndex:indexPath.row withObject:t.socketLowbgColor];
    }
}else{

    mwCell.sellRate.backgroundColor=[cellrc objectAtIndex:indexPath.row];
    mwCell.sellRate.textColor=([[cellrc objectAtIndex:indexPath.row] isEqual:t.socketLowbgColor])?t.socketLowfgColor:t.socketHighfgColor;
}

mwCell.buyRate.text=[NSString stringWithFormat:@"%.2f",br_nxtVal];
mwCell.sellRate.text=[NSString stringWithFormat:@"%.2f",sr_nxtVal];

浮点值类似于 2396.250000

4

3 回答 3

1

尝试像这样比较

#define kVerySmallValue (0.000001)
  if(fabsf(br_nxtVal - br_preVal) < kVerySmallValue) {
  //// Your code
  }
于 2013-06-13T06:27:40.030 回答
1

通过Deafult,如果您必须将它分配给变量,那么像这样3.13的十进制值,请执行以下操作:doublefloat

float f = 3.14f;//now it is float

看这个例子:

float f = 3.14;
if(f == 3.14)
{
   NSLog(@"Equal");
}
else
{ 
   NSLog(@"Not Equal");
}

它会打印不等于..

所以最好的方法是:

float f = 3.14;
    if(f == 3.14f)
    {
       NSLog(@"Equal");
    }
    else
    { 
       NSLog(@"Not Equal");
    }
于 2013-06-13T06:56:33.520 回答
0

比较浮点值的最佳方法是使用范围

if(4.0<=a&&a<=4.5)

或者你可以使用fabs(number)< comparator >fabs(number)

于 2013-06-13T06:02:49.490 回答