๐[CH2/01] ๊ฐ๋จํ ํ๋ก๊ทธ๋๋ฐ ๊ตฌํ
๐[Notion] ๊ฐ๋จํ ํ๋ก๊ทธ๋๋ฐ ๊ตฌํ
ํ์ ๊ธฐ๋ฅ๋ง ๊ตฌํํ์ด์ ํ์ด ๊ฐ์๋ฅผ ๋ณด๋ฉด์ ๋์ ๊ธฐ๋ฅ์ ๊ณต๋ถํ๋ค.
์ฌ์ฉ์๊ฐ ์ ๋ ฅํ ์ซ์ ๋ฐฐ์ด์ ์ ๋ ฌํ๋ ํ๋ก๊ทธ๋จ์ ๊ตฌํํด๋ณด์ธ์.
algorithm ํค๋์ sort ํจ์๋ฅผ ์ฌ์ฉํ์ง ์๊ณ ์ง์ ๊ตฌํํด๋ณด์ธ์.#include <iostream>
using namespace std;
// ๋งค๊ฐ๋ณ์(ํ๋ผ๋ฏธํฐ)๋ก ๋ฐฐ์ด์ ๋ฐ๋ ํจ์ ์ ์ธ
void printArray(int numbers[], int size)
{
for (int i = 0; i < size; i++)
{
cout << numbers[i] << " ";
}
cout << endl; // ์ถ๋ ฅ ํ ์ค๋ฐ๊ฟ
}
// ํฉ๊ณ๋ฅผ ๋ฐํํ๋ ํจ์
int getSum(int numbers[], int size)
{
int sum = 0; // ํฉ๊ณ๋ฅผ ๋ด์ ๋ณ์ ์ ์ธ ๋ฐ ์ด๊ธฐํ
// ๋ฐฐ์ด์ ๋๋ฉด์ ํฉ๊ณ ๊ตฌํ๊ธฐ
for (int i = 0; i < size; i++) // ๋ฐฐ์ด์ ํฌ๊ธฐ๋งํผ ๋ฐ๋ณต
{
sum += numbers[i]; // ๋ฐฐ์ด์ ๊ฐ ์์๋ฅผ ํฉ์ฐ
}
return sum; // ํฉ๊ณ ๋ฐํ
}
// ํ๊ท ์ ๋ฐํํ๋ ํจ์
double getAverage(int numbers[], int size)
{
// ํ๊ท == ์ดํฉ / ๊ฐ์
// ์ ์ / ์ ์ == ์ ์ -> ํ๋๋ฅผ ์ค์ํ์ผ๋ก ํ๋ณํ
return getSum(numbers, size) / static_cast<double>(size);
// return static_cast<double>)(getSum(numbers, size)) / size;
}
// ๋ฒ๋ธ์ ๋ ฌ ํจ์ (์ค๋ฆ์ฐจ์)
void sortAsc(int numbers[], int size)
{
// ๋ค์๊ฐ ์ ๋ ฌ๋๋ฉด ๋ง์ง๋ง ํ์ ์์ ๊ฐ์ฅ ์ ์ซ์๋ ์ด๋ฏธ ์ ์ผ ์์ ์๋ผ ์ ๋ ฌ ์ ํด๋ ๋จ
for (int i = 0; i < size - 1; i++) // i๋ ํ ํ์
{
for (int j = 0; j < size - 1 - i; j++) // j๋ ์ด ํ์
{
if (numbers[j] > numbers[j + 1])
{
// Swap
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
}
// ๋ฒ๋ธ ์ ๋ ฌ ํจ์ (๋ด๋ฆผ์ฐจ์)
void sortDesc(int numbers[], int size)
{
for (int i = 0; i < size - 1; i++)
{
for (int j = 0; j < size - 1 - i; j++)
{
if (numbers[j] < numbers[j + 1])
{
// Swap
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
}
int main()
{
// ์ฌ์ฉ์๋ก๋ถํฐ ์ ์ 5๊ฐ๋ฅผ ์
๋ ฅ๋ฐ์ ๋ฐฐ์ด์ ์ ์ฅ
const int SIZE = 5; // ๋ฐฐ์ด์ ํฌ๊ธฐ๋ฅผ 5๋ก ๊ณ ์
int numbers[SIZE] = {}; // ๋ฐฐ์ด ์์ฑ ๋ฐ ์ด๊ธฐํ
int sortChoice = 0;
// 5๋ฒ ๋๋ฉด์ ์ฌ์ฉ์์๊ฒ ์ ์๊ฐ์ ์
๋ ฅ ๋ฐ์
for (int i = 0; i < SIZE; i++)
{
cout << i + 1 << "๋ฒ์งธ ์ซ์ ์
๋ ฅ: ";
cin >> numbers[i];
}
printArray(numbers, SIZE); // ํจ์์ ๋ฐฐ์ด์ ์ฃผ์์ ๋ฐฐ์ด์ ํฌ๊ธฐ๋ฅผ ๋งค๊ฐ๋ณ์๋ก ๋๊น
cout << "์ดํฉ: " << getSum(numbers, SIZE) << endl;
cout << "ํ๊ท : " << getAverage(numbers, SIZE) << endl;
cout << "์ค๋ฆ์ฐจ์: 1๋ฒ, ๋ด๋ฆผ์ฐจ์: 2๋ฒ";
cin >> sortChoice;
if (sortChoice == 1)
{
sortAsc(numbers, SIZE); // sortAsc()๋ ์ ๋ ฌ๋ง ์ํ, return ๊ฐ ์์
}
else if (sortChoice == 2)
{
sortDesc(numbers, SIZE);
}
else
{
cout << "1๋ฒ, 2๋ฒ ์ค์ ์ ํํ์ธ์." << endl;
}
// ์ ๋ ฌ ํจ์๋ค์ ์ ๋ ฌ๋ง ์ํ, return ๊ฐ ์์
// ์ฌ๊ธฐ์ ์ถ๋ ฅ
printArray(numbers, SIZE);
return 0;
}
printArray ํจ์ ์์ for ๋ฐ๋ณต๋ฌธ์ ๋ฐฐ์ด์ ๊ฐ ์์๋ฅผ ํ๋์ฉ ์ถ๋ ฅํ๋ ์ญํ ์ ํ๋ค.
๋ฐฐ์ด ํฌ๊ธฐ๋งํผ ๋ฐ๋ณตํ๋ฉด์ ๋ฐฐ์ด์ ๊ฐ ์ธ๋ฑ์ค๋ฅผ ์ถ๋ ฅํ๋ค.
void printArray(int numbers[], int size)
{
for (int i = 0; i < size; i++)
{
cout << numbers[i] << " "; // ๋ฐฐ์ด์ ๊ฐ ์์ ์ถ๋ ฅ
}
cout << endl;
}
// ๋ฆฌํด ๊ฐ์ด ์์ด์ ์ถ๋ ฅ ์ ๋จ
cout << "์ค๋ฆ์ฐจ์: "" << sortAsc << endl;