Menu
CoddyTech

분기와 범위

Coddy의 Lua 개발자를 위한 C++ 코스 레슨. 48개 중 8번째.

Lua에서는 각 블록을 end로 닫고, 중간 분기는 elseif로 표기하며, 조건식이 없습니다. 따라서 cond and a or b가 조건식 대신 사용되지만 a가 false 또는 nil이면 제대로 작동하지 않습니다. C++에서는 중괄호와 else if 체인, 조건 연산자 cond ? a : b를 사용하며, 조건이 참이면 a에 무엇이 들어 있든 a를 반환합니다. 조건은 괄호 안에 넣으며, if/else 체인에서는 한 분기만 실행됩니다.

Lua

local score = 8
local result
if score >= 10 then
  result = "high"
elseif score >= 5 then
  result = "mid"
else
  result = "low"
end
local parity = score % 2 == 0 and "even" or "odd"
print(result .. " " .. parity)

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>

int main(){
int x=7;
std::string size;
if(x>=10){size="high";}
else if(x>=5){size="mid";}
else{size="low";}
std::cout<<size<<" "<<(x%2==0?"even":"odd")<<"\n";
}

각 프로그램을 독립적으로 추적해 보세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스와 대상의 출력이 일치한다고 가정하지 마세요.

challenge icon

챌린지

쉬움

입력: 정수 온도. 10 미만이면 cold, 10부터 24까지는 mild, 25 이상이면 hot을 반환하세요.

exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일 모두 편집할 수 있습니다. 공개 시그니처는 그대로 유지하세요. 잠긴 main.cpp는 stdin을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API 동작도 독립적으로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력과 결과는 signed int 범위에 들어갑니다. 별도 언급이 없는 한 텍스트는 ASCII입니다.

직접 해보기

#include "exercise.hpp"
#include <iostream>
int main(){

std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int n;in>>n;std::cout<<weather(n)<<"\n";
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Lua 개발자를 위한 C++의 모든 레슨

직접 연습해 보세요: 온라인 C++ 컴파일러