2011-08-06 68 views
0

当我试图计算两个UITextFields的百分比时,我在UITextField中收到消息“NAN”。我当前的代码如下:在UITextField中接收错误消息

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

firstFloat的值是什么?我怀疑这是零。 – taskinoor

+0

我想知道是否需要使用某种形式的“IF”语句。 – TWcode

回答

0

我强烈怀疑这是IBOutlet连接的问题。以下代码适用于我:

@interface testViewController : UIViewController { 
    UITextField *tf1; 
    UITextField *tf2; 
    UILabel *result; 
} 

@end 

@implementation testViewController 

- (void)dealloc{ 
    [tf1 release]; 
    [tf2 release]; 
    [result release]; 
    [super dealloc]; 
} 

-(void) click:(id) obj { 
    float firstFloat = [tf1.text floatValue]; 
    float secondFloat = [tf2.text floatValue]; 
    float answer = secondFloat/firstFloat * 100; 
    result.text = [NSString stringWithFormat:@"%.1f%%",answer]; 
} 

-(void) viewWillAppear:(BOOL)animated { 

    tf1 = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 200, 30)]; 
    tf1.backgroundColor = [UIColor whiteColor]; 

    tf2 = [[UITextField alloc]initWithFrame:CGRectMake(10, 50, 200, 30)]; 
    tf2.backgroundColor = [UIColor whiteColor]; 

    result = [[UILabel alloc]initWithFrame:CGRectMake(10, 90, 200, 30)]; 
    result.backgroundColor = [UIColor whiteColor]; 

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    btn.frame = CGRectMake(10, 130, 50, 30); 
    [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside]; 
    [self.view addSubview:btn]; 

    [self.view addSubview:tf1]; 
    [self.view addSubview:tf2]; 
    [self.view addSubview:result]; 

} 

@end 
1

NaN意味着不是一个数字。它表明您的计算不会生成有效的数字。我的第一个猜测是firstFloat0,这意味着你试图除以零。反过来,这可能是由self.tex15nil造成的 - 请检查您的IBOutlet连接是否正确。

+0

IBOutlet似乎很好。这部分代码位于IBAction ID发件人中。它用作buttontap,在点击的UITextField内添加+1。当我不点击tex15或tex16时显示NAN。 – TWcode