我正在学习 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 的向量时它会起作用,但它没有当我只想使用一个变量来存储单个平面时。
第一种方法有什么问题?
抱歉英语不好。
我已将您的问题编辑为英语,以便其他人可以理解它。
我希望你接受它,因为我会用英语回答。
您在函数中传递对象的副本,因此定义的实际值不会改变。相反,您应该传递一个指向它的指针,然后修改该指针指向的对象。planexy
points_input()
planexy
main()
修改后的代码:
前向声明
void points_input(plane* planexy); // ingreso_puntos function
代码
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");
}
}
使用指针时,您使用的->
不是.
仅用于对象的点。
为什么它使用数组作为您的第二个代码?
简单地说,数组/向量本身就是实际的指针。
证明: scanf("%f", &planexy[0].pt[i].x);
与scanf("%f", &planexy->pt[i].x);
.
在main()
. 你应该通过地址的planexy
它创建的指针。
points_input(&planexy);
提示:当您想通过函数修改对象时,您可以像使用scanf
. 否则,当您只想读取一个对象时,您可以正常传递它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句