2015-02-23 45 views
0

我正在使用Objective-C在xcode中製作計算器我在語法中使用了float,但是我希望當答案是浮點計算器時顯示浮點類型不是整數,我希望當答案是整數時它顯示整數當答案是浮動它顯示浮動。 這裏是代碼 價值https://github.com/syntaxxerrorr/Calculator我想使用整數和float-objective-c中的相同功能?

+0

所以你的措辭這是有點混亂。當你不使用整數時你不想要一個浮點數嗎? 只要總是使用一個浮點數,並且當你需要一個整數就可以了。 我其實早就做了一個計算器,所以改寫一下你問了一下,我可以在我的代碼中查找:) – gikygik 2015-02-23 17:34:27

+1

聽起來像是格式化問題。爲所有內部計算和值選擇一個內部表示。浮球是一個很好的選擇。數字結果總是以字符串形式呈現給用戶。在生成格式正確的字符串時,使用NSNumberFormatter可獲得最大的功能。 – danh 2015-02-23 17:55:11

回答

0
  1. 測試是否是int或沒有。你可以這樣說:

    if (fmod(fVal, 1.0) == 0.0) // is integer

  2. 獲取整數結果:

    int result = (int)roundf(myFloat);

顯示相應的值,使用條件。

+0

這是我的代碼。 https://github.com/syntaxxerrorr/Calculator – 2015-02-24 15:49:07

+0

你能指出你正在做的這個方法/類嗎? – sasquatch 2015-02-24 15:54:03

+0

等功能 – 2015-02-24 15:55:05

0

例如:

float answer = 12.0; 
float truncAnswer; 
int intAnswer; 

truncAnswer = truncf(answer); 
intAnswer = (int)truncAnswer; 

if(answer == truncAnswer) 
{ 
    NSLog(@"Integer Answer = %d", intAnswer); 
}else{ 
    NSLog(@"Float Answer = %f", answer); 
} 

如果更改答案以12.0初始化,將打印整數答案。

+0

這裏是源代碼請檢查並幫助我 https://github.com/syntaxxerrorr/Calculator – 2015-02-24 15:48:17

0

你知道Objective-C中的NSNumber是一個代表Float,Double,Int,Integer等的類嗎?所以你可以在你的函數中返回NSNumber。

讓我們嘗試使用它。

+0

這裏是我的代碼.. https://github.com/syntaxxerrorr/Calculator – 2015-02-24 15:49:40

相關問題