我正在学习数组,我想尝试的是首先让用户输入 x,y 值 4 次 例如
第一次
x = 1
y = 3
第二次
x = 2
y = 3
第三次
x = 3
y = 1
第四次
x = 1
y = 3
.然后将用户输入 4 次的值存储在数组中并打印出来,但我得到了一些奇怪的输出。
我的输出
10001711642800 <-- some weird output
预期输出
1,3
2,3
3,1
1,3
代码(不工作)
int x;
int y;
//request the user to enter x and y value 4 times.
for (int i=1; i<5; i++) {
cout << i << "Please enter x-cord." << endl;
cin >> x;
cout <<i << "Please enter y-cord." << endl;
cin >> y;
}
//intitalize the array size and store the x,y values
int numbers[4][4] = {
x, y
};
//loop through 4 times to print the values.
for (int i = 0; i<5; i++) {
cout << numbers[i][i];
}
我知道它可以用 vector 来完成,但现在我正在尝试使用数组,因为我不擅长使用数组。
最佳答案
你在这里混淆了很多东西。
- 在您的
for
循环中,您将在循环的每次迭代中覆盖存储在x
和y
中的值。 int numbers[4][4]
创建一个包含总共 16 个元素的二维数组。你想要的是int numbers[4][2]
。- 您的数组初始化不完整,因为
x
和y
只包含用户输入的最后两个值,而不是全部 8 个值。
要解决此问题,您应该在 for
循环之前创建数组,然后将用户输入的值直接存储到数组中。
关于c++ - 将输入存储到数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19420092/