我正在学习如何创建结构,但我被困在我制作的程序上。一切正常,直到我尝试输入“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”时: