(C++) 6.2 배열과 반복문

이준우·2021년 10월 17일
0
post-custom-banner
#include <iostream>

using namespace std;

int main()
{
	const int num_students = 5;

	int score0 = 84;
	int score1 = 95;
	int score2 = 76;
	int score3 = 81;
	int score4 = 56;

	int total_score = score0 + score1 + score2 + score3 + score4;

	double avg_score = static_cast<double>(total_score) / num_students;

	return 0;

}

이를 배열로 바꿔보자.

#include <iostream>

using namespace std;

int main()
{
	const int num_students = 5;

	int scores[num_students]{ 84, 95, 76, 81, 56 };
	int total_score = 0;
	for (int i = 0; i < num_students; i++)
	{
		total_score += scores[i];
	
	}

	double avg_score = static_cast<double>(total_score) / num_students;

	cout << avg_score << endl;

	/*int score0 = 84;
	int score1 = 95;
	int score2 = 76;
	int score3 = 81;
	int score4 = 56;

	int total_score = score0 + score1 + score2 + score3 + score4;

	double avg_score = static_cast<double>(total_score) / num_students;
*/
	return 0;

}

output : 78.4

array와 반복문은 뗄수가 없는 구조!!!

profile
꿈꾸는 CV
post-custom-banner

0개의 댓글