1

我正在学习如何创建结构,但我被困在我制作的程序上。一切正常,直到我尝试输入“2”。当程序打印符号时,它应该是“He”,但会打印“Helium”。我无法弄清楚出了什么问题以及为什么要打印he.symbol并且he.name全部在一行中。链接到下面的图片。

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

struct Element {
    int num;
    double mass;
    char symbol[2];
    char name[20];
};


int main()
{
    struct Element h;
    h.num = 1;
    h.mass = 1.008;
    strcpy(h.symbol, "H");
    strcpy(h.name, "Hydrogen");

    struct Element he;
    he.num = 2;
    he.mass = 4.0026;
    strcpy(he.symbol, "He");
    strcpy(he.name, "Helium");

    int number;

    printf("Please enter the number of the element you want info on. \n");
    scanf("%d", &number);

    if (number == 1 /*&& !(number > 1)*/) {
        printf("Atomic Number: %d \n", h.num);
        printf("Atomic Mass: %.3f \n", h.mass);
        printf("Atomic Symbol: %s \n", h.symbol);
        printf("Atomic Name: %s \n", h.name);
    } else if (number == 2) {
        printf("Atomic Number: %d \n", he.num);
        printf("Atomic Mass: %.3f \n", he.mass);
        printf("Atomic Symbol: %s \n", he.symbol);
        printf("Atomic Name: %s \n", he.name);
    } else {
        printf("Invalid number! \n");
        printf("Or that element hasn't been added to the date base yet. \n");
        printf("Try back later \n");
    }

    return 0;
}

当我输入“2”时: 当我输入 2

4

1 回答 1

1

您只分配Element.symbol了 2 个字节,它只能存储只有一个字符的字符串,因为另一个字符将用于空字符。symbol[3]元素周期表中元素的符号不超过2个字符,应写“ ”。此外,如果您想为所有 118 个元素分配值,您的代码可能会变得非常混乱。您可以编写如下代码:

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

struct Elements {
    int num;
    double mass;
    char symbol[3];
    char name[20];
};

void print(struct Elements element)
{
    printf("Atomic Number: %d \n", element.num);
    printf("Atomic Mass: %.3f \n", element.mass);
    printf("Atomic Symbol: %s \n", element.symbol);
    printf("Atomic Name: %s \n", element.name);
}

void assignElement(struct Elements *givenElement, int num, float mass, char symbol[3], 
char name[20])
{
    givenElement->num=num;
    givenElement->mass=mass;
    strcpy(givenElement->symbol,symbol);
    strcpy(givenElement->name,name);
}

int main()
{
    struct Elements element[119];
    assignElement(&element[1], 1, 1.008, "H", "Hydrogen");
    assignElement(&element[2], 2, 4.06, "He", "Helium");
    assignElement(&element[3], 3, 6.09, "Li", "Lithium");

    int number;

    printf("Please enter the number of the element you want info on. \n");
    scanf("%d", &number);

    if (number < 119 && number > 0) {
        print(element[number]);
    } 
    else {
        printf("Invalid number! \n");
        printf("Or that element hasn't been added to the date base yet. \n");
        printf("Try back later \n");
    }
    return 0;
}
于 2021-01-20T10:33:58.763 回答