所以我有pow
- 一個包含數字的列表。我必須檢查像這樣的其他數字:獲取所有數字並將pow
中的數字與具有相同索引的數字相加。基於變量的第n個字符沒有按預期工作
因此,如果我檢查號碼4552
我需要得到pow[4]+pow[5]+pow[5]+pow[2]
。因爲我是一個noob,我嘗試將數字轉換爲string
,使用循環獲取字符,然後轉換回int
以獲取索引。因此,代碼是獲得4550和4559之間的金額如下:
for (int i = 4550; i < 4560; i++)
{
int sum = 0;
for (int j = 0; j < i.ToString().Length; j++)
{
sum += pows[Convert.ToInt32(i.ToString()[j])]; //here is the error - index was out of range
//do something with sum (like store it in another list)
}
}
那麼,什麼是錯?
編輯:爲了避免混淆... pow
有10個元素,從索引0-9。
SOLUTION:我的代碼的問題是,我得到的字符代碼不是數字本身,感謝史蒂夫萊麗斯。雖然Dmitry Bychenko提供的解決方案遠遠勝於我的嘗試。謝謝你們。
哇,這很奇怪。它嘗試了'sum + = ...'後再次死於同樣的錯誤,但我把一個'console.writeline(x);'並得到49(?!) – fishmong3r
更新我的答案,因爲我剛剛意識到發生了什麼:) –