2018. 7. 25. 01:28
728x90

구조체를 이용해 5명의 국영수의 평균을 구하시오

struct student
{
	char	name[30];
	float	korean;
	float	english;
	float	math;
	float	avg;
};

int main()
{
	struct student *ptr_student_new = NULL;
	int students = 5;

	ptr_student_new = (struct student*) malloc(sizeof(struct student) * students);

	*(ptr_student_new + 0) = { "Lee", 81, 79, 99, 0 };
	*(ptr_student_new + 1) = { "Kim", 80, 82, 78, 0 };
	*(ptr_student_new + 2) = { "Park", 79, 85, 75, 0 };
	*(ptr_student_new + 3) = { "Hong", 75, 87, 82, 0 };
	*(ptr_student_new + 4) = { "Jung", 90, 89, 65, 0 };

	struct student average = { 0, };

	for (int i = 0; i < students; i++) 
	{
		average.korean = average.korean + (ptr_student_new + i)->korean;
		average.english = average.english + (ptr_student_new + i)->english;
		average.math = average.math + (ptr_student_new + i)->math;
	}

	average.korean = average.korean / 5;
	average.english = average.english / 5;
	average.math = average.math / 5;

	cout << "국어 평균: " << average.korean << "\n";
	cout << "영어 평균: " << average.english << "\n";
	cout << "수학 평균: " << average.math << "\n";

	free(ptr_student_new);

	return 0;
}

 malloc으로 동적할당할 한 후의 활용에 대한 연습문제. 문제를 푸는 것 자체는 어렵지 않았으나 malloc의 크기를 따로 구해서 for문을 돌리려는 삽질을 하느라 시간이 조금 걸렸다. 생각해보면 동적할당은 애초에 어느정도로 할당할지에 대한 값이 있을테니 해당 값을 별도로 저장해서 관리하면 될 일이었다. _msize(void)라는 함수를 알아내긴 했지만 비표준이라 사용하기도 곤란한 함수였다. 애초에 동적할당은 변수를 이용해서 하거나 특정 값을 이용해서 할테니 그 값만 따로 관리해주면 될 일이어서 결과적으로 삽질을 한게 되었다. 



728x90

'공부 > 기타' 카테고리의 다른 글

자료구조 2장. 연습문제 05  (0) 2018.07.25
자료구조 2장. 연습문제 04  (0) 2018.07.25
xor을 이용한 스왑  (0) 2018.03.20
[엑셀] 반올림/올림/내림 (ROUND)  (0) 2017.11.05
[엑셀] 특수 합계 계산(SUMPRODUCT)  (0) 2017.11.01
Posted by 아야카