【发布时间】:2019-01-25 00:39:26
【问题描述】:
我正在学习 C 编程,我正在尝试编写一个简单的程序来存储 XY 平面中的点。
一开始我是这样做的:
#include<stdio.h>
#include<stdlib.h>
typedef struct point { float x, y; } PNT;
typedef struct plane
{
int n_points;
PNT pt[50];
} plane;
void points_input(plane planexy);
void points_distance(plane planexy);
int main()
{
plane planexy;
printf("How many points do you want to enter? : ");
scanf("%d", &planexy.n_points);
points_input(planexy);
points_distance(planexy);
}
void points_input(plane planexy)
{
int i;
for (i = 0; i < planexy.n_points; i++)
{
printf("\nEnter a coordinate for x%d ", i);
scanf("%f", &planexy.pt[i].x);
printf("\nEnter a coordinate for y%d ", i);
scanf("%f", &planexy.pt[i].y);
system("cls");
}
}
void points_distance(plane planexy)
{
int i;
printf("Select first point :\n");
for (i = 0; i < planexy.n_points; i++)
{
printf("\n %d.(%.1f ,%.1f)", i, planexy.pt[i].x, planexy.pt[i].y);
}
}
而且它不起作用,当我尝试访问某个点的某个变量时,它总是返回 0。
在弄乱了变量名称“planexy”并将其用作大小为 1 的向量,然后将所有提及它的内容都用作 planexy[0] 之后,它突然开始工作了:
#include<stdio.h>
#include<stdlib.h>
typedef struct point { float x, y; } PNT;
typedef struct plane
{
int n_points;
PNT pt[50];
} plane;
void points_input(plane planexy[]);
void points_distance(plane planexy[]);
int main()
{
plane planexy[1];
printf("How many points do you want to enter? : ");
scanf("%d", &planexy[0].n_points);
points_input(planexy);
points_distance(planexy);
}
void points_input(plane planexy[])
{
int i;
for (i = 0; i < planexy[0].n_points; i++)
{
printf("\nEnter a coordinate for x%d ", i);
scanf("%f", &planexy[0].pt[i].x);
printf("\nEnter a coordinate for y%d ", i);
scanf("%f", &planexy[0].pt[i].y);
system("cls");
}
}
void points_distance(plane planexy[])
{
int i;
printf("Select first point :\n");
for (i = 0; i < planexy[0].n_points; i++)
{
printf("\n %d.(%.1f ,%.1f)", i, planexy[0].pt[i].x, planexy[0].pt[i].y);
}
}
现在,这段代码可以工作了,但我不知道为什么我必须这样写才能让它发挥作用,而且它看起来不像是好的代码。
我知道如果我想使用多个平面“XY”我应该将变量存储为一个向量,但我只想使用一个,我不明白为什么当我使用大小为 1 的向量时它会起作用但是当我只想使用一个变量来存储一个平面时,它不会。
第一种方法有什么问题?
抱歉英语不好。
【问题讨论】:
-
你的第一个代码不可能返回任何东西,因为它甚至没有编译。