简体   繁体   English

函数中的结构

[英]Structures in functions

I am new to structures and I have a task to first make a structure "Points" that holds x and y (DONE) then make a function printPoint() that would print the points made in main (DONE) and then I must make a function Point createPoint(double x, double y) that would create a Point type structure, fill it in with coordinates and return it, so the p1 and p2 variables in main would be made with createPoint() , how do I exactly do that?我是结构的新手,我的任务是首先创建一个包含 x 和 y (DONE) 的结构“点”,然后创建一个函数printPoint()来打印 main (DONE) 中的点,然后我必须做一个函数Point createPoint(double x, double y)将创建一个 Point 类型结构,用坐标填充并返回它,所以 main 中的 p1 和 p2 变量将使用createPoint() ,我该怎么做?

#include <stdio.h>
#include <stdlib.h>

typedef struct Point {
    int x;
    int y;
} Point;

void printPoint(Point p1, Point p2) {
    printf("%d %d\n%d %d", p1.x, p1.y, p2.x, p2.y);
}

Point createPoint(double x, double y) {
    ?
}

int main()
{
    Point p1 = {2.0, -3.0};
    Point p2 = {-4.0, 5.0};
    printPoint(p1, p2);
}

It's as simple as that:就这么简单:

Point createPoint(double x, double y) {
  Point point = {x, y};
  return point;
}
...
printPoint(createPoint(1,2), createPoint(3,4));
... 

But double should probably be int here.但是double应该在这里是int Or maybe struct Point should contain double fields rather than int fields.或者struct Point应该包含double字段而不是int字段。 Only you know the answer.只有你知道答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM