2013-05-04 21 views
3

我做下面的代碼時,他們打我的應用程序計算按鈕:無法做計算並獲得打印出標記

float sqft = ([textfield1.text floatValue]); 
    float thick= ([textfield2.text floatValue]); 
    float cos = ([textfield3.text floatValue]); 
    float eff = ([textfield4.text floatValue]); 

    float num = ((thick*.5)*sqft)/eff; 
    float cost = (num*cos); 
    float costft = (cost/sqft); 

    label1.text = [NSString stringWithFormat:@"%2.f",num]; 
    label2.text = [NSString stringWithFormat:@"%2.f",cost]; 
    label3.text = [NSString stringWithFormat:@"%2.f",costft]; 

當我做這個標籤只返回零。我已經設置標籤爲maually作爲字符串只是爲了看看它是否是代表團的事情,但我無法弄清楚爲什麼我的公式只返回零。

+0

也許你想'.2f'?另外,確保'eff!= 0.0f'和'sqft!= 0.0f'。此外,'NSLog'的值或'num','cost'和'costft'確保它們給你正確的值。 – msgambel 2013-05-04 05:15:13

+0

請發佈數量,成本,costft的NSLog值。 – 2013-05-04 05:23:09

+0

@VenkatManoharPerepa,sqft的數據類型是: - > float sqft =([textfield1.text floatValue]); – 2013-05-04 05:28:10

回答

3

問題出在你用%2f的方式代碼,

%2.f以2號碼格式給出答案的四捨五入值。如果你的答案小於或等於0.5。那麼你得到0作爲答案。

現在它應該工作

float sqft = ([textfield1.text floatValue]); 
float thick= ([textfield2.text floatValue]); 
float cos = ([textfield3.text floatValue]); 
float eff = ([textfield4.text floatValue]); 

float num = ((thick*.5)*sqft)/eff; 
float cost = (num*cos); 
float costft = (cost/sqft); 

label1.text = [NSString stringWithFormat:@"%2f",num]; 
label2.text = [NSString stringWithFormat:@"%2f",cost]; 
label3.text = [NSString stringWithFormat:@"%2f",costft]; 
+0

不,我用這個@「%2.f」 – 2013-05-04 05:33:53

3

它在我結束工作的正確。但是,在一個情況下,你會得到ZERO值時,你的價值是0.786676這樣..

textfield1.text = @"123.89"; 
    textfield2.text= @"123.00"; 
    textfield3.text= @"123.7"; 
    textfield4.text= @"123"; 


    float sqft = ([textfield1.text floatValue]); 
    float thick= ([textfield2.text floatValue]); 
    float cos = ([textfield3.text floatValue]); 
    float eff = ([textfield4.text floatValue]); 

    float num = ((thick*.5)*sqft)/eff; 
    float cost = (num*cos); 
    float costft = (cost/sqft); 

    NSLog(@"Num : %@",[NSString stringWithFormat:@"%2.f",num]); 
    NSLog(@"Cost : %@",[NSString stringWithFormat:@"%2.f",cost]); 
    NSLog(@"Costft : %@",[NSString stringWithFormat:@"%2.f",costft]); 

輸出

人數:62 費用:7663 Costft:62

1

你想要將小數點後的數字限制爲兩位 - 這就是爲什麼你使用.2f,對吧?如果是這樣,你應該使用這個@"%.2f"

就試試這個:

label1.text = [NSString stringWithFormat:@"%.2f",num]; 
label2.text = [NSString stringWithFormat:@"%.2f",cost]; 
label3.text = [NSString stringWithFormat:@"%.2f",costft]; 
相關問題