【问题标题】:Index out of bound. How to resolve索引超出范围。如何解决
【发布时间】:2020-06-20 14:28:55
【问题描述】:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Please enter the Principal: ");
        int principal = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Please enter the rate: ");
        int rate = Convert.ToInt32(Console.ReadLine());

        int a = rate / 100;
        int b = a * principal;
        int x = b + principal;

        int[] sample = {};

        Console.WriteLine("How long do you want the loop to run: ");
        int loop = Convert.ToInt32(Console.ReadLine());

       // StringBuilder sb = new StringBuilder();

        for (int i = 0; i <= loop; i++)
        {

            sample[x] = x;

           // sb.AppendLine(x.ToString());
            b = a * x;
            x = b + x;
        }
        Console.WriteLine(sample);
    }
 }
}

您好,我刚开始学习 C#,今天老师讨论的主题是数组。所以我决定创建一个简单的利息计算器,但它给了我

“System.IndexOutOfRangeException:索引超出了数组的范围。”

【问题讨论】:

  • 仅供参考 Console.WriteLine(sample) 不会给你有用的信息。而是使用Console.WriteLine(string.Join(", ", sample));
  • 我完全按照你告诉我的做了,但它仍然显示同样的错误。

标签: c# arrays for-loop


【解决方案1】:

做这样的事情

    Console.WriteLine("How long do you want the loop to run: ");
    int loop = Convert.ToInt32(Console.ReadLine());

    int[] sample = new int[loop];

从数组中设置长度

并将您的 for 循环从 (int i = 0; i loop; i++) 更改为 (int i = 0; i loop; i++)

【讨论】:

  • 它仍然显示相同的错误。顺便说一句,删除“=”运算符与任何事情有什么关系。
  • @Fakhr 因为循环从 0 开始,如果你想循环多次,你想在它到达循环之前停止。因此,如果它是 4,您希望它循环 0、1、2、3 而不是 0、1、2、3、4
【解决方案2】:

您必须分配足够的空间:int[] sample = new int[loop];

数组在 C# 中从零开始索引,因此如果数组的长度为 X,则最后一个元素的索引为 X-1。所以你的 for 循环应该是:for (int i = 0; i &lt; loop; i++)

您正在使用x 索引您的sample 数组,但我认为您不想使用i 对其进行索引。 sample[i] = x;

您正在打印一个数组,但它会输出System.Int32[]。我想你想打印出数组中的元素。

static void Main(string[] args)
{
    Console.WriteLine("Please enter the Principal: ");
    int principal = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("Please enter the rate: ");
    int rate = Convert.ToInt32(Console.ReadLine());

    int a = rate / 100;
    int b = a * principal;
    int x = b + principal;

    Console.WriteLine("How long do you want the loop to run: ");
    int loop = Convert.ToInt32(Console.ReadLine());

    int[] sample = new int[loop];

    for (int i = 0; i < loop; i++)
    {
        sample[i] = x;
        b = a * x;
        x = b + x;
    }

    for (int i = 0; i < sample.Length; i++)
        Console.WriteLine(sample[i]);
}

【讨论】:

  • 它正在工作,但它没有给我正确的输出。它只是打印 1000 次十次。如果我给出原则 = 1000,速率 = 5 和循环 = 10,那么我希望答案是:
  • 1. 1050.0 2. 1102.5 3. 1157.62 等等。我首先用 Python 编写了这段代码,它运行良好。
  • 如果rate = 5,那么int a = rate / 100 将为0。:)
  • 我犯了一个非常尴尬的错误。感谢您指出这一点。
猜你喜欢
  • 2014-07-11
  • 2021-10-01
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
相关资源
最近更新 更多