将 oct 转换为 dex 整数
Convert oct to dex integer
数字转换不正确
在程序中您需要将八进制数系统转换为十进制数
“a”是使用 GetDex() 方法的整数 class 字段
构造 - 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;
}
问题出在
Convert.ToInt32(Convert.ToString(a)[i])
片段。您实际上添加了 ascii 代码,而不是 数字 。要从 character '5'
中得到数字 integer 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');
数字转换不正确 在程序中您需要将八进制数系统转换为十进制数 “a”是使用 GetDex() 方法的整数 class 字段 构造 - 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;
}
问题出在
Convert.ToInt32(Convert.ToString(a)[i])
片段。您实际上添加了 ascii 代码,而不是 数字 。要从 character '5'
中得到数字 integer 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');