2017-02-07 42 views
1

錯誤在這一行當我給字符串值超過10個數字是顯示溢出異常?? 在Visual Studio 整個代碼做如下int no = Int32.Parse(s1);

string s1 = s.ToString(); 

int no = Int32.Parse(s1); 
int r = 0; 
int sum = 0; 
for (int i = 0; i <s1.Length; i++) 
{ 
    r = no % 10; 
    sum = sum + r; 
    no = no/10; 
} 
+1

嘗試Int64.Parse(s1); – jose

+0

只要使用'long.Parse(s1)',你需要在轉換之前檢查'int.MaxValue'。 –

+0

thnkx但如果長期使用,我不能做%操作它在這裏我的邏輯去無用,所以?? –

回答

1

假設你喜歡你目前的數據類型,你需要一些驗證。

先鑄成小數再檢查範圍。

decimal d; 
bool ok = decimal.TryParse(s.ToString(), out d); 
if (!ok) throw new FormatException("Blah blah"); 
if (d > Int32.MaxValue || d < Int32.MinValue) throw new ArgumentOutOfRangeException("Blah blah"); 
int no = Convert.ToInt32(d); 
相關問題