錯誤地轉換數字在程式中你需要從八進制數系統轉換為十進制“a”是一個整數類欄位,它使用了GetDex()方法構造- this.a = a;
public int GetDex()
{
int res = 0;
int exp = 1;
for (int i = Convert.ToString(a).Length - 1; i >= 0; i--)
{
res = exp * Convert.ToInt32(Convert.ToString(a)[i]);
exp *= 8;
}
return res;
}
uj5u.com熱心網友回復:
問題出在
Convert.ToInt32(Convert.ToString(a)[i])
分段。您實際上添加的是ascii 代碼,而不是數字。要從字符中獲取數字整數 5,只需減去: '5''0'
(Convert.ToString(a)[i] - '0')
您的代碼已更正:
public int GetDex()
{
int res = 0;
int exp = 1;
for (int i = Convert.ToString(a).Length - 1; i >= 0; i--)
{
//DONE: you should add digits, not ascii codes: - '0'
res = exp * (Convert.ToString(a)[i] - '0');
exp *= 8;
}
return res;
}
您可以在Linq的幫助下將其壓縮:
public int GetDex() => a
.ToString()
.Aggregate(0, (s, i) => s * 8 i - '0');
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/385760.html
