程序在初始化期间未与数组一起运行
Program not running with Array during Initialization
我只是在练习使用数组。所以我的程序包括将数据类型为双倍的数字输入到数组中并将它们打印出来。简单。
我只将数字限制在 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]
做某事时,你会得到未定义的行为。在您的试用版中,幸运的是,未定义的行为只导致了一些垃圾输出。
相关文章:
- 为什么我不能将 rand() 与数组的大小一起使用?
- 如何将 std::find() 与 2d std: 数组一起使用?
- 程序在初始化期间未与数组一起运行
- 将 find_if() 与数组一起使用的代码段中出错
- 是否可以将isdigit,isalpha函数与输入的字符串数组一起使用
- 将MPI_Scatter与 char* 数组一起使用
- 在模板参数中使用 auto:一些使用示例和..如何使其与恒定大小的 C 数组一起使用
- 将模板气泡排序与结构数组一起使用时出现问题
- 将'sort'与字符数组一起使用 (C++)
- Strncpy只能与固定长度的数组一起使用
- 关于结构和将它们与数组一起使用
- 如何将while循环与数组一起使用
- 将"getline"与数组一起使用
- 将输入流迭代器与数组一起使用
- 将指针与动态数组一起使用时出现问题
- 如何将 printf 与 2D 数组一起使用
- 函数更改后指针的显示值与数组 C 一起改变
- 如何将 boost::crc_optimal 与二进制数组(0 和 1 的数组)一起使用
- 是否可以将两个多维数组一起添加到第三个多维数组中
- 如何声明一个将string和int数组一起排序的函数?