You have assigned Element.symbol
with only 2byte which can only store string with only one character as the other character will be used for null character. You should write "symbol[3]
" as the symbol of elements in periodic table are no longer than 2 characters. Also, your code can become quite messy if you want to assign values for all 118 elements. You can write your code like below:
#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
", element.num);
printf("Atomic Mass: %.3f
", element.mass);
printf("Atomic Symbol: %s
", element.symbol);
printf("Atomic Name: %s
", 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.
");
scanf("%d", &number);
if (number < 119 && number > 0) {
print(element[number]);
}
else {
printf("Invalid number!
");
printf("Or that element hasn't been added to the date base yet.
");
printf("Try back later
");
}
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…