我正在学习数组,我想尝试的是首先让用户输入x,y值4次,例如
第一次
x = 1
y = 3
Run Code Online (Sandbox Code Playgroud)
第二次
x = 2
y = 3
Run Code Online (Sandbox Code Playgroud)
第三次
x = 3
y = 1
Run Code Online (Sandbox Code Playgroud)
第四次
x = 1
y = 3
Run Code Online (Sandbox Code Playgroud)
.然后将用户键入的值存储在数组中4次并打印出来但我得到了一些奇怪的输出.
我的输出
10001711642800 <-- some weird output
Run Code Online (Sandbox Code Playgroud)
预期产出
1,3
2,3
3,1
1,3
Run Code Online (Sandbox Code Playgroud)
代码(不工作)
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];
}
Run Code Online (Sandbox Code Playgroud)
我知道它可以用向量完成,但现在我正在尝试使用数组,因为我在使用数组方面很弱.
你在这里混淆了很多东西.
for-loop中,你将覆盖存储在循环的每次迭代中x和存储的值y.int numbers[4][4]创建一个包含总共16个元素的二维数组.你想要的是什么int numbers[4][2].x并且y只包含用户输入的最后两个值,而不是全部8.要解决此问题,您应该在for-loop 之前创建数组,然后将用户直接输入的值存储到数组中.