[英]Im getting System.ArgumentOutOfRangeException error in C#?
我正在做一项学校作业,我必须将 8 位二进制数转换为十进制数。 这是我的代码;
private void btnCalculate_Click(object sender, EventArgs e)
{
string invoer = txtBoxInput.Text;
// binair naar decimaal
if (rdBtnBinair.Checked == true)
{
int invoerlengte = invoer.Length;
double nieuwgetal = 0;
for (int i = 0; i <= invoerlengte; i++)
{
if (int.Parse(invoer.Substring(i, 1)) == 1)
{
nieuwgetal += Math.Pow(2,(i+1));
}
}
txtBoxOutput.Text = nieuwgetal.ToString();
在 C# 中。 我得到错误:System.ArgumentOutOfRangeException:索引和长度必须引用字符串中的位置。
认为我的代码应该不错,看不出有什么问题。 问候
你可能想改变这个:
for (int i = 0; i <= invoerlengte; i++)
对此:
for (int i = 0; i < invoerlengte; i++)
因为当i
等于invoer.Length
时,下一行代码将寻找字符串末尾之后的下一个字符,这超出了范围:
invoer.Substring(i, 1)
这是因为您的 foreach 循环一次迭代太多,因为您使用<=
而不是 '<'。
在这些情况下,检查何时发生什么总是好的。 您可以使用调试器或普通的旧Console.WriteLine
(或 debug.log w/e)来执行此操作
在线示例: https://dotnetfiddle.net/UyE2rw
public static void Main()
{
var invoer = "12345";
int invoerlengte = invoer.Length;
double nieuwgetal = 0;
for (int i = 0; i <= invoerlengte; i++)
{
Console.WriteLine("i: " + i + ", substring: " + invoer.Substring(i, 1));
if (int.Parse(invoer.Substring(i, 1)) == 1)
{
nieuwgetal += Math.Pow(2,(i+1));
}
}
}
输出:
i: 0, substring: 1
i: 1, substring: 2
i: 2, substring: 3
i: 3, substring: 4
i: 4, substring: 5
Run-time exception (line 13): Index and length must refer to a location within the string.
Parameter name: length
Stack Trace:
[System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length]
at System.String.Substring(Int32 startIndex, Int32 length)
at MyApp.Main() :line 13
请注意 - 索引从 0 开始,从 1 开始计数。因此 substring(0,1) 是索引 0 处的字符,但它是字符串数组中的第一个元素 (char)。
item1 在 index0,item2 在 index1 等等。
德groetjes!
private void btnCalculate_Click(object sender, EventArgs e)
{
string invoer = txtBoxInput.Text;
int invoerlengte = invoer.Length;
double nieuwgetal = 0;
if (rdBtnBinair.Checked == true)
{
for (int i = 1; i <= invoerlengte; i++)
{
if (int.Parse(invoer.Substring(invoerlengte - (1 * i), 1)) == 1)
{
nieuwgetal += Math.Pow(2, (i - 1));
}
}
}
txtBoxOutput.Text = nieuwgetal.ToString();
}
这是解决方案,现在可以使用。 再见!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.