【问题标题】:Getting a "NAN" error message within a UITextField在 UITextField 中获取“NAN”错误消息
【发布时间】:2011-10-22 17:37:24
【问题描述】:

我遇到了 UITextField 中的错误消息的重大问题。我有一个 IBAction buttontap id sender 设置,当我点击 UITextField 并点击 buttontap 时,它会将值 +1 添加到所选的 UITextField。我的问题是我的 UITextField,当我点击其他 UITextFields 时,我设置了两个 UITextfields 之间的百分比给我一个“NAN”错误消息。我以为我已经解决了这个问题,直到我添加了更多代码。这是我当前的代码:

- (IBAction)buttonTap:(id)sender { 
    int value = [currentText.text intValue] + 1;
    currentText.text = [NSString stringWithFormat:@"%d",value];

    int n7 = [tex.text intValue]; 
    int n8 = [tex2.text intValue];
    int n9 = [tex3.text intValue];
    int n10 = [tex4.text intValue];
    int n11 = [tex5.text intValue];
    int n12 = [tex6.text intValue];
    int r = n7 + n8 + n9 + n10 + n11 + n12;
    NSString *rn = [NSString stringWithFormat:@"%d",r];
    [tex13 setText:rn]; 

    int n1 = [tex7.text intValue]; 
    int n2 = [tex8.text intValue];
    int n3 = [tex9.text intValue];
    int n4 = [tex10.text intValue];
    int n5 = [tex11.text intValue];
    int n6 = [tex12.text intValue];
    int s = n1 + n2 + n3 + n4 + n5 + n6;
    NSString *sn = [NSString stringWithFormat:@"%d",s];
    [tex14 setText:sn]; 



    float firstFloat = [self.tex15.text floatValue]; 
    float secondFloat = [self.tex16.text floatValue]; 
    float answer = secondFloat / firstFloat * 100; 
    self.tex20.text = [NSString stringWithFormat:@"%.1f%%",answer];   
}

【问题讨论】:

  • firstFloat 的计算结果是否为 0?如果是这样,您将收到“除以零”错误。
  • 问题不在于您向我们展示的代码。我们不知道textex2、...tex16 的值是什么。如果它们未初始化或 tex15 为 0,那就可以解释了。
  • 那我该如何解决呢?我需要使用 if 语句吗?

标签: iphone ios4 iphone-sdk-3.0 cocos2d-iphone


【解决方案1】:

是 NAN 还是 NaN? NaN 代表非数字,当您的数学结果导致无法用数字表示的内容时将被打印。正如评论中指出的那样,除以零会给你一个 NaN。

解决它非常简单:找出除以零的位置,或者导致 NaN 的任何原因,然后使用 if/else 语句来测试这些值。然后替换一个新值或将错误消息字符串传递给解释情况的标签。

编辑:

可能看起来像这样:

    float firstFloat = [self.tex15.text floatValue]; 
    float secondFloat = [self.tex16.text floatValue]; 

    NSString *labelOutput;

    if (firstFloat == 0.0)
    {
        labelOutput = NSLocalizedString(@"Error", @"Error while dividing by zero");
    }

    else 
    {
        float answer = secondFloat / firstFloat * 100; 
        labelOutput = [NSString stringWithFormat:@"%.1f%%",answer];

    }

    self.tex20.text = labelOutput;

【讨论】:

  • 当然,有一个简单的给你。
猜你喜欢
  • 2011-10-21
  • 2021-09-25
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
  • 2013-02-07
  • 1970-01-01
相关资源
最近更新 更多