2012-08-26 82 views
0

一個計算器。每次點擊數字按鈕時,標籤都會附加到「displaystring」可修飾字符串。我注意到,在輸入相同數字的11位數字後,floatValue或intValue函數給了我相同的錯誤。問題與intvalue,floatValue

self.lbldisplay.text正確顯示了顯示字符串的內容。但 的intValue或的floatValue甚至NSCanner公用事業返回,進入10位後,同樣的錯誤

這裏的代碼和日誌:

// original 
[self.displayString appendString: [NSString stringWithFormat: @"%i", [sender tag]]]; 

else { // new entry  
    //origin test 
    [self.displayString setString:@""]; 
    [self.displayString appendString: [NSString stringWithFormat: @"%i", [sender tag]]]; 
    bIsTypingANumber = TRUE; 
} 

// fCurrentNumber = [self.displayString floatValue]; 
// [self display:fCurrentNumber]; 
// self.lblDisplay.text = displayString; 

NSString *numberString; 

NSString *str = [NSString stringWithString:displayString]; 

NSScanner *theScanner = [NSScanner scannerWithString:str]; 

[theScanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil]; 
[theScanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&numberString]; 

NSLog(@"Attempts: %i", [numberString integerValue]); 

self.lblDisplay.text = str; 

輸出:

2012-08-26 17:23:34.264 Pilots Fuel[4989:f803] Attempts: 1 
2012-08-26 17:23:34.400 Pilots Fuel[4989:f803] Attempts: 11 
2012-08-26 17:23:34.552 Pilots Fuel[4989:f803] Attempts: 111 
2012-08-26 17:23:34.800 Pilots Fuel[4989:f803] Attempts: 1111 
2012-08-26 17:23:34.936 Pilots Fuel[4989:f803] Attempts: 11111 
2012-08-26 17:23:35.072 Pilots Fuel[4989:f803] Attempts: 111111 
2012-08-26 17:23:35.216 Pilots Fuel[4989:f803] Attempts: 1111111 
2012-08-26 17:23:35.344 Pilots Fuel[4989:f803] Attempts: 11111111 
2012-08-26 17:23:35.488 Pilots Fuel[4989:f803] Attempts: 111111111 
2012-08-26 17:23:35.632 Pilots Fuel[4989:f803] Attempts: 1111111111 
2012-08-26 17:23:35.776 Pilots Fuel[4989:f803] Attempts: 2147483647 
2012-08-26 17:23:36.056 Pilots Fuel[4989:f803] Attempts: 2147483647 

回答

3

它是因爲你溢出了整數數據類型,它只能保存從-2147483648到2147483647(32位大小)的值。數據類型double可以保存較大的值,但最終會失去精度。

嘗試

NSLog(@"Attempts: %lli", [numberString longLongValue]); 

將使用的精度爲64位,將允許數字的更大的數字。

+0

幹得好 - 我得到了相同的「錯誤」,但是很久以後,這個數字非常龐大。 THAAAAAAAANNNKSSS :-))))) –

0

歡迎來到SO。請寫下清楚說明您的問題的問題。另外,如果您提供代碼示例,請確保它們的格式正確,以便其他人更容易閱讀它們。

請注意,您正在使用intfloat,它們都有大小限制。他們不能代表所有可能的數字。你可以使用雙精度和64位整數,但它們也有一個限制。如果你真的需要更大的數字,看看NSDecimalNumber是否適合你的用例。它有一個限制(雖然相當大)。

如果你需要更大的數字,你需要使用一個支持任意大數字的庫。

+0

感謝您的回答 - 我試圖瞭解本網站的用戶界面,這並不總是清楚。謝謝您的回答 。 –