程序在初始化期间未与数组一起运行

Program not running with Array during Initialization

本文关键字:数组 一起 运行 初始化 程序      更新时间:2023-10-16

我只是在练习使用数组。所以我的程序包括将数据类型为双倍的数字输入到数组中并将它们打印出来。简单。

我只将数字限制在 4 个。所以数组,num_List[3]在代码中。我已经确保正确使用 for 循环来读取和打印结果。

前几次我测试了代码。我意识到数组中的第 4 个数字是科学记数法,告诉我我忘了将array初始化为0,在本例中0.0,因为我使用的是double.所以我输入了这段代码。

for (index = 0; index <= 3; index++)
num_List[index] = 0.0;

此代码应该已将num_List数组初始化为0.0。但是,当我对此进行测试时,在我输入 4 个数字后没有任何结果。所以我在这里犯了一个逻辑错误,或者是 for 循环的其他原因导致它被捕获并且不继续执行。

我在书中读到过这种特殊的初始化方式。

#include <iostream>
using namespace std;
int main() {
double num_List[3]; // These are my variables
int index;
//double num; // Ignore these two for now, for they are to be modified later on.
//double result;
cout << "This program will summarize the numbers you've inputted print out the result. n";
cout << "And also print out the address of the 1st and 4th address in the array." << endl;
cout << "Please enter the four numbers to be summarized.";
for (index = 0; index <= 3; index++) { // I put this in after I realized my mistake of not initializing my arrays to 0.0.
num_List[index] = 0.0;} // This is where the problem is, I think. 
for (index = 0; index <= 3; index++) // This reads in the user the input
cin >> num_List[index];
cout << "The numbers you have inputted is:n";
for (index = 0; index <= 3; index++) // This prints out the array.
cout << num_List[index] << ", " << endl;
return 0;
}

如果您专注于上述代码并尝试编译它,您会发现不幸的是,在您输入 4 个数字后,我的代码不会从那里继续,无论是还是键入一个数字并将其间隔为 4 个数字,或者输入一个数字,按这些数字的 Enter 键。很可能我犯了一个明显的错误,但我在看到它时遇到了一些麻烦。

我使用代码块,所以与我以前用来练习代码的Bloodshed C++编译器相比,情况略有不同。

double num_List[3];

这将声明一个包含3个元素的数组,索引为 0 到 2。

for (index = 0; index <= 3; index++)

这将循环遍历 4 个索引,从 0 到3。当你用num_List[3]做某事时,你会得到未定义的行为。在您的试用版中,幸运的是,未定义的行为只导致了一些垃圾输出。