[C++][백준 17293] 맥주 99병

PublicMinsu·2024년 11월 29일
0

문제

접근 방법

반복문을 활용하여 N부터 1까지를 출력해 준 뒤 마지막에 더 이상 남아있지 않음을 출력해 주면 되는 문제입니다.

조심해야 할 점은 맥주가 몇 병인지에 따라 출력하는 값이 조금씩 달라진다는 점입니다.

코드

#include <iostream>
using namespace std;
int N;

string GetBottle(int cnt)
{
    switch (cnt)
    {
    case 0:
        return "no more bottles";
    case 1:
        return "1 bottle";
    default:
        return to_string(cnt) + " bottles";
    }
}

int main()
{
    ios::sync_with_stdio(0), cin.tie(0);
    cin >> N;
    for (int i = N; i > 0; --i)
    {
        string bottles = i - 1 == 0 ? "no more" : to_string(i - 1);

        cout << GetBottle(i) << " of beer on the wall, " << GetBottle(i) << " of beer.\n"
             << "Take one down and pass it around, " << GetBottle(i - 1) << " of beer on the wall.\n\n";
    }

    cout << "No more bottles of beer on the wall, no more bottles of beer.\n"
         << "Go to the store and buy some more, " << GetBottle(N) << " of beer on the wall.";
    return 0;
}

풀이

0병, 1병, 그 외로 나누어서 병에 대한 표현이 달라집니다.
이는 반복문 안에 있는 문장뿐만 아니라 마지막에 출력해야 하는 문장에서도 유효함을 주의해야 합니다.

profile
연락 : publicminsu@naver.com

0개의 댓글