【问题标题】:Structure in a Structure and Array结构和数组中的结构
【发布时间】:2019-11-18 21:49:05
【问题描述】:

我对以下作业有一些问题:

一) 定义一个新的数据类型 tpos 用于存储实体在二维平面中的位置 单精度。之后定义另一个新的数据类型 tsolid 可以存储 双精度实体及其在二维平面中的位置。使用 tpos 来定义 tsolid 的位置分量。 b) 定义一个长度为 2 的 tsolid 类型的数组。两个固体的位置和重量(数组 元素)现在应使用 scanf 函数从键盘读取。用于检查 程序的正确性,在屏幕上显示数组内容。

到目前为止我有:

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

struct tpos
{
   float xy

};

struct tsolid
{
    struct tpos;
    double m;
};

int main()
{
    struct tsolid array[2];


    return 0;
}

我现在该如何进行?已经尝试了一些事情,但遗憾的是他们没有成功。文本基本上说我必须在 1 个数组元素中保存 1 个实体,对吗?但是我怎样才能将 pos x 、 pos y 和重量 m 全部保存在 1 个数组元素中,然后同时打印它们呢?我必须使用指针吗?

【问题讨论】:

  • 你在float xy之后缺少;
  • 不应该tpos 有两个成员,比如float x; float y;
  • tsolid 中,您需要为struct tpos 元素命名。

标签: c arrays database data-structures


【解决方案1】:

首先,如果你需要存储“二维平面”,你应该使用struct里面的两个元素。


另一件事是你不能通过说struct tpos; 来访问struct 元素 - 你应该使用tpos xy


修复代码:

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

struct tpos
{
   float x;
   float y;
};

struct tsolid
{
    tpos xy;
    double m;
};

int main()
{
    tsolid array[2];
    return 0;
}

当涉及到scanf 和显示内容时,您需要自行决定“输出布局”。
您可以使用

访问“元素”的某些部分
array[i].m;
array[i].xy.x;
array[i].xy.y;

【讨论】:

  • 感谢您的遮阳篷。我忘记了 x 和 y 之间的逗号,我的意思是有两个元素。您的第二个建议非常有帮助。程序现在运行,我稍后会发布。如果您还可以解释或澄清为什么我可以将多个值保存在一个数组元素中,我将非常感激。到目前为止,我假设 1 个数组元素 = 1 个值。我认为这是让我失望的大事
  • 每个元素都有一个结构。每个结构都有几个成员。
【解决方案2】:

tpos 需要两个成员,每个坐标一个。

tsolid 需要 tpos 成员的名称。

然后编写一个循环询问每个值,将它们放入数组中,然后编写另一个循环打印数组中的值。

#include <stdio.h>

struct tpos
{
    float x, y;

};

struct tsolid
{
    struct tpos position;
    double mass;
};

int main()
{
    struct tsolid array[2];

    for (int i = 0; i < 2; i++) {
        printf("Enter x, y, and mass for object %d:\n", i+1);
        scanf("%f %f %lf", &array[i].position.x, &array[i].position.y, &array[i].mass);
    }

    printf("You entered:\n");
    for (int i = 0; i < 2; i++) {
        scanf("x = %f, y = %f mass = %lf\n", array[i].position.x, array[i].position.y, array[i].mass);
    }

    return 0;
}

【讨论】:

  • 是的,我理解。我们现在不应该使用循环,我知道为什么,但我现在可以手动完成。感谢您的帮助。
猜你喜欢
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 2010-10-27
  • 1970-01-01
相关资源
最近更新 更多