Bài 80. Giới thiệu về kiểu dữ liệu struct trong lập trình C


Tóm tắt


Trong lập trình C, một cấu trúc (hoặc struct) là một tập hợp các biến (có thể có nhiều kiểu khác nhau) dưới một tên duy nhất.

Cú pháp của struct

struct structureName

{

dataType member1;

dataType member2;

...

};

Ví dụ và khai báo:


struct Person

{

char name[50];

int citNo;

float salary;

};


int main()

{

struct Person person1, person2, p[20];

return 0;

}

Hoặc:


struct Person

{

char name[50];

int citNo;

float salary;

} person1, person2, p[20];

Video giải thích chi tiết  về kiểu dữ liệu struct trong lập trình C trong lập trình C | Tự học lập trình C



Code ví dụ


#include "stdio.h"

struct Date{
	int day;
	int month;
	int year;
};

void inputDate(struct Date &d){
	printf("Nhap vao ngay: ");
	scanf("%d", &d.day);
	printf("\nNhap vao thang: ");
	scanf("%d", &d.month);
	printf("\nNhap vao nam: ");
	scanf("%d", &d.year);
}

void printDate(struct Date d){
	printf("%d/%d/%d", d.day, d.month, d.year);
}

int checkDate(struct Date d){
	if (d.day<0 || d.month<0 || d.year <0)
		return 0;
	
	if(d.month>12)
		return 0;
		
	if (d.month==2){
		if(d.day>28)
			return 0;
	}
	
	if (d.month==1|| d.month==3 || d.month==5|| d.month==7|| d.month==8|| d.month==10|| d.month==12){
		if(d.day>31)
			return 0;
	}
	
	if(d.day>30)
		return 0;
	
	return 1;
}

int main(){
	struct Date myDate;
	inputDate(myDate);
	printf("\n---\n");
	printDate(myDate);
	printf("Kiem tra ngay hop le: %s", checkDate(myDate)==1?"HOP LE":"KHONG HOP LE");
	
}


    

Bạn có thể thích những bài đăng này:

Không có nhận xét nào:

Đăng nhận xét