C++/문제풀이

[C++] 함수를 이용하여 커피잔 수 구하기

year.number 2022. 5. 25. 23:25

 

[C++ 200제 024번]

문제: 200원짜리 커피 자판기에 800원을 넣으면 몇 잔이 나오는지 구하는 함수를 만들자.

 


내가 짠 코드

//
//  coffee.cpp
//  function
//
//  Created by yeonsu on 2022/05/25.
//

#include <iostream>
using namespace std;

//커피 1잔 값 기호상수로 선언
const int cupOfCoffee = 200;
const int Money = 800;

//함수 원형
int coffeeMachine(int x, int y);

int main(){
    
    int inputMoney;
    cout << "커피 한 잔이 " << cupOfCoffee << "원일 때, 800원을 자판기에 넣으면" << endl;
    cout << coffeeMachine(Money, cupOfCoffee) << "잔이 나온다." << endl;
    
    return 0;
}

//함수 정의
int coffeeMachine(int x, int y){
    return x / y;
}

정석

**사용자에게 금액을 입력받는 것으로 변형

 

//
//  coffee.cpp
//  function
//
//  Created by yeonsu on 2022/05/25.
//

#include <iostream>
using namespace std;

//함수 원형
int coffee (int money);

//기호상수 선언
const int cupOfCoffee = 200;        //커피 1잔 = 200원

int main(){
    
    cout << "현재 갖고 있는 돈을 입력하세요: ";
    int inputMoney;
    cin >> inputMoney;
    
    cout << "커피 한 잔이 " << cupOfCoffee << "일 때, ";
    cout << inputMoney <<"원을 자판기에 넣으면 " << coffee(inputMoney)<<"잔이 나온다." << endl;
    
    
    return 0;
}

int coffee (int money){
    if(money < 200)
        return -1;
    else
        return money / 200;
    
}

함수 알고리즘

int coffee (int money){
    if(money < 200)
        return -1;
    else
        return money / 200;

1. 함수 coffee의 매개변수 int money는 main 함수에서 inputMoney와 같다.

2. 만약 갖고 있는 돈이 200원(커피 한 잔)보다 적다면 종료

3. 200원보다 많다면 money / 200원

 


실행결과