在 D 语言中使用索引和索引变量的问题

问题描述 投票:0回答:1

任何可以提供帮助的人。我是D语言的初学者。我面临着无法解决的索引违规问题。该程序的逻辑似乎是正确的,因为 C 和 C++ 中类似的东西可以工作(我已经测试过它)。

这是代码:

import std.stdio;

void main()
{
    float[8][4] NOTAS;
    int I, J;

    writeln("2D ARRAY - INPUT AND OUTPUT\n");

    for (I = 0; I < 8; I++)
    {
        writefln("Enter grades for student %d:", I + 1);
        for (J = 0; J < 4; J++)
        {
            writef("Grade ==> %d: ", J + 1);
            readf(" %f", &NOTAS[I][J]);
        }
        writeln();
    }

    writeln("\nGRADE REPORT\n");
    writeln("Student Grade1 Grade2 Grade3 Grade4");
    writeln("------- ------ ------ ------ ------");

    for (I = 0; I < 8; I++)
    {
        writef("%7d", I + 1);
        for (J = 0; J < 4; J++)
        {
            writef("%7.1f", NOTAS[I][J]);
        }
        writeln();
    }
}

以下是程序运行的步骤以及遇到的错误信息:

2D ARRAY - INPUT AND OUTPUT

Enter grades for student 1:
Grade ==> 1: 1
Grade ==> 2: 1
Grade ==> 3: 1
Grade ==> 4: 1

Enter grades for student 2:
Grade ==> 1: 2
Grade ==> 2: 2
Grade ==> 3: 2
Grade ==> 4: 2

Enter grades for student 3:
Grade ==> 1: 3
Grade ==> 2: 3
Grade ==> 3: 3
Grade ==> 4: 3

Enter grades for student 4:
Grade ==> 1: 4
Grade ==> 2: 4
Grade ==> 3: 4
Grade ==> 4: 4

Enter grades for student 5:
[email protected](16): Range violation
----------------
??:? onRangeError [0x45cbb9]
/home/runner/TreasuredThoughtfulAssembler/main.d:16 _Dmain [0x4150dd]
Grade ==> 1: exit status 1
 

有没有人经历过这种情况并可以分享他们的见解?预先感谢您。

注意:我正在 Replit 上运行测试。

我已经尝试将循环流程从“I = 0; I < 8; I++" to "I = 0; I <= 7; I++". I have also tried changing the dimension of the variable NOTAS from "[8][4]" to "[9][5]", but nothing has had any effect. The impression I got is that the variable "I" progresses from 0 to 4, and when it reaches 5, it violates the index of NOTAS.

indexing d
1个回答
1
投票

C 以一种奇怪的方式处理数组的数组,其中使用镜像声明。 D 始终以一致的顺序执行此操作:

int[5] x;
是一个 5 长度整数数组,
int[5][4]
是一个由 5 长度整数数组组成的 4 长度数组。

因此,C 中的使用与 D 中的使用相反。

C: int a[5][4];最大索引:a[4][3]; D:int[5][4];最大索引:a[3][4];

© www.soinside.com 2019 - 2024. All rights reserved.