2012-01-05 167 views
0

出於某種原因,我下面的代碼行返回一個0公式不要算計

int bac = [food.text intValue] * 12 * 0.042 * 5.14/[weight.text intValue] * 0.73; 

我似乎無法找出原因。食物和體重都是UITextFields。任何幫助將非常感激。

它與int需要成爲一個浮點數有什麼關係嗎?或雙?

這裏是我的整個方法:

-(IBAction) calcBac { 

    float bac = [food.text floatValue] * 12 * 0.042 * 5.14/[weight.text floatValue] * 0.73; 
    NSString *msg = [[NSString alloc] initWithFormat: @"Results: You're BAC is %d", bac]; 
    result.text = msg; 
    [msg release]; 

} 
+1

給出你獲得零的'food.text'和'weight.text'的例子。 – 2012-01-05 05:05:39

回答

3

有兩件事情:

  • 確保你的數據類型是一致的。最好使用float,以便在計算中不會丟失小數部分,但不能轉身嘗試用int格式化程序(%d)顯示它。

因此,要清理例如:

float bac = [food.text floatValue] * 12 * 0.042 * 5.14/[weight.text floatValue] * 0.73; 
NSString *msg = [[NSString alloc] initWithFormat: @"Results: You're BAC is %.2f", bac]; 

%.2f格式化說,以顯示與浮動小數點後2位。

  • 操作順序。如果該值仍然不正確,請認識到(按書面)每個操作將按順序執行。如果你需要組合操作(比如你真的想把整個第一部分除以整個第二部分),然後爲分組添加括號。

換句話說,可能是你真正的意思是(雖然我不知道):

float bac = ([food.text floatValue] * 12 * 0.042 * 5.14)/([weight.text floatValue] * 0.73); 
NSString *msg = [[NSString alloc] initWithFormat: @"Results: You're BAC is %.2f", bac]; 

沒有任何分組,運行計算器的號碼你給一百六十零分之五例子,我得到〜0.059的結果。如果這不是你正在尋找的輸出,你可能會錯過一些分組符號。

HTH

+0

很好的解釋,我正在學習回答問題;它會有所幫助 – 2012-01-05 06:42:43

2

嘗試在float收集的結果,也可能是小於一個

+0

我試過了。我的結果(當食物= 5和體重= 160)是1073741824. – TopChef 2012-01-05 05:13:40

0
int bac = [food.text intValue] * 12 * 0.042 * 5.14/[weight.text intValue] * 0.73; 

在該行weight.text是一個int,所以它會做在其前面的數的整數除法。因此,如果這個值:

[food.text intValue] * 12 * 0.042 * 5.14 

小於這個值:

[weight.text intValue] 

你會得到零每次。