我正在学习数组,我想尝试的是首先让用户输入 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];
}
我知道这可以用向量来完成,但现在我正在尝试使用数组,因为我在使用数组方面很弱。
你在这里混淆了很多事情。
- In your
for
-loop 您将覆盖存储在中的值x
and y
在循环的每次迭代中。
-
int numbers[4][4]
创建一个总共包含 16 个元素的二维数组。你想要的是int numbers[4][2]
.
- 您的数组初始化不完整,因为
x
and y
仅包含用户输入的最后两个值,而不是全部 8 个。
要解决此问题,您应该在for
-loop 然后将用户直接输入的值存储到数组中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)