将变量存储在带有变量的二维数组中

时间:2014-02-14 02:01:08

标签: c arrays variables

首先,我想开始说我是一名学生,并且不熟悉编码。所以,我提前为我在这个部门缺乏知识而道歉....

我正在尝试编写将以整数读取并将其存储在多维数组中的代码。整数是图表上的点,x& y值。另外,我希望数组大小是用户输入的变量(如用户输入的点数 - points [numPoints] [2])。这就是我到目前为止所做的:

#include <stdio.h>
int main()
{

int numPoints=0, row, colm;
int points[numPoints][2];





printf("This program will read in a number of points, and calculate the distance between them.\n");
printf("It will also calculate the total distance between the first point, and the last point.\n");
printf("\nHow many points will you be entering?\n");
scanf(" %d", &numPoints);
printf("Please enter each point individually.\nExample(x & y values shown):\nx y\n3 5\n-2 10\netc...\nPlease enter your points now (press 'Enter' after each point):\n");
for (row = 0; row<numPoints; row++)
{
    for (colm = 0; colm<2; colm++)
    {
            scanf("%d", &points[row][colm]);
    }
}
printf("These are the points recorded:\n");
for (row = 0, colm=0; row<numPoints; row++)
{
    printf("(%d,%d)\n", points[row][colm],points[row][colm+1]);
}

return 0;
}

我现在已经运行了几次,这是我得到的输出。它要么没有正确存储数字,要么没有正确打印它们。

This program will read in a number of points, and calculate the distance between them.
It will also calculate the total distance between the first point, and the last point.

How many points will you be entering?
4
Please enter each point individually.
Example(x & y values shown):
x y
3 5
-2 10
etc...
Please enter your points now (press 'Enter' after each point):
1 2
3 4
5 6
7 8
These are the points recorded:
(1,2)
(3,4)
(6,31)
(1,8)
Program ended with exit code: 0

有谁能告诉我我做错了什么?

谢谢

2 个答案:

答案 0 :(得分:0)

我希望此代码能为您提供帮助:

  #include <stdio.h>
  int main()
 {

  int  numPoints =0,row, colm;
  int points[10][2];

   printf("This program will read in a number of points, and calculate the distance between them.\n");
  printf("It will also calculate the total distance between the first point, and the last point.\n");
  printf("\nHow many points will you be entering?\n");
  scanf(" %d", &numPoints);
  printf("Please enter each point individually.\nExample(x & y values shown):\nx y\n3 5\n-2 10\netc...\nPlease enter your points now (press 'Enter' after each point):\n");

for (row = 0; row < numPoints; row++)
{
    for (colm = 0; colm<2; colm++)
    {
            scanf("%d", &points[row][colm]);
    }
}
printf("These are the points recorded:\n");
for (row = 0, colm=0; row<numPoints; row++)
{
    printf("(%d,%d)\n", points[row][colm],points[row][colm+1]);
}

return 0;
}

答案 1 :(得分:0)

移动

int points[numPoints][2];

之后
scanf(" %d", &numPoints);

E.g

scanf(" %d", &numPoints);
int points[numPoints][2];