2011-08-06 89 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