Machineboy空
C++ 기초 문법 다지기 예제 모음3 - 조건문 처리 본문
프로그램에서 의사결정은 어떻게 해야 할까?
조건에 맞지 않는 값이 들어왔을 때 행동해야 할 일을 정의하고 싶을 때, if-else 문 사용하기
양자택일 이상의 선택을 해야할 때, if - else if - else,
선택해야하는 경우가 많다면 switch문 등 경우에 따라 사용하면 된다.
예제 14. 세금 계산기
문제)
주 이름이 WI 인 경우 세율을 5.5%
위스콘시 거주자에 해당하는 소계, 세율, 합계 금액을 출력하지만
다른 주에 거주하는 경우에는 합계 금액만 출력한다.
조건)
- else문 사용 불가
출력)
What is the order amount? 10
What is the state? WI
The subtotal is $10.00
The tax is $0.55
The total is $10.55
What is orter amount? 10
What is the state? MN
The total is $10.55
#include <iostream>
#include <string>
using namespace std;
int orderAmount, subtotal;
float tax = 0.55;
string state;
int main() {
cout << "What is the order amount?";
cin >> orderAmount;
cout << "What is the state?";
cin >> state;
if(state == "WI"){
cout << "The subtotal is $" + to_string(orderAmount) + "\n";
cout << "The tax is $";
printf("%.2f",orderAmount + tax);
cout <<"\n";
cout << "The total is $";
printf("%.2f",orderAmount + tax);
return 0;
}
cout << "The total is $";
printf("%.2f",orderAmount + tax);
}
예제 15. 암호 검증
출력)
What is the password: 12345
That password is incorrect.
What is the password: asb$123
Welcome!
#include <iostream>
#include <string>
using namespace std;
string pw;
int main() {
cout << "What is the password: ";
cin >> pw;
if(pw == "asb$123"){
cout << "Welcome!";
}else{
cout << "That password is incorrect.";
}
}
예제 16. 합법적으로 운전 가능한 연령
출력)
What is your age? 15
You are not old enough to legally drive
What is your age? 35
You are old enough to legally drive.
#include <iostream>
#include <string>
using namespace std;
int age, legalAge = 16;
int main() {
cout << "What is your age?";
cin >> age;
if(age >= legalAge){
cout << "You are old enough to legally drive.";
}else{
cout << "You are not old enough to legally drive.";
}
}
예제 17. 혈중 알코올 농도 계산기
출력)
Your BAC is 0.08
It is not legal for you to drive.
#include <iostream>
#include <string>
using namespace std;
float a,w,rF= 0.6,rM = 0.73,h;
string gender;
float BAC(float a, float w, float h, string gender){
if(gender == "m"){
float bac = ( a * 5.14 / w * rM) - 0.015 * h;
return bac;
}else{
float bac = ( a * 5.14 / w * rF) - 0.015 * h;
return bac;
}
}
int main() {
cout << "alcohol";
cin >> a;
cout << "weight";
cin >> w;
cout << "gender";
cin >> gender;
cout << "drinksAfter";
cin >> h;
if(BAC(a,w,h,gender)>=0.08){
cout << "It is not legal for you to drive.";
return 0;
}
cout << "OK";
}
예제 18. 온도 변환
출력)
Press C to convert from Fahrenheit to Celsius.
Press F to convert from Celsius to Fahrenheit.
Your choice: C
Please enter the temperature in Fahrenheit: 32
The temperature in Celsius is 0.
#include <iostream>
#include <string>
using namespace std;
int convert(int temperature, char key) {
if (key == 'c') {
int F = (temperature * 9 / 5) + 32;
return F;
}
if (key == 'f') {
int C = (temperature - 32) * 5 / 9;
return C;
}
return 0;
}
int main() {
char key;
int temperature;
cout << "Press C to convert from F to C\n";
cout << "Press F to convert from C to F\n";
cin >> key;
cout << "Your choice: " << key << endl;
if (key == 'c') {
cout << "Please enter the temperature in Fahrenheit: ";
cin >> temperature;
cout << "The temperature in Celsius is " << convert(temperature, 'c') << endl;
} else if (key == 'f') {
cout << "Please enter the temperature in Celsius: ";
cin >> temperature;
cout << "The temperature in Fahrenheit is " << convert(temperature, 'f') << endl;
} else {
cout << "Invalid choice! Please press 'C' or 'F'." << endl;
}
}
예제 19. BMI 계산기
출력)
Your BMI is 19.5.
You are within the ideal weight range.
또는
Your BMI is 32.5.
You are overweight. You should see your doctor.
#include <iostream>
#include <string>
using namespace std;
string BMI (float w, float h){
float bmi = (w / (h * h));
string answer = "";
if( bmi>=18.5 && bmi <= 25){
answer = "You are within the ideal weight range.";
}else if(bmi > 25){
answer = "넌 돼지!";
}else{
answer = "넌 멸치!";
}
return answer;
}
float weight, height;
int main() {
cout << "Your weight: ";
cin >> weight;
cout << "Your height: ";
cin >> height;
// m단위라고 함
height = height / 100;
cout << BMI(weight, height);
}
예제 20. 여러 주를 지원하는 세금 계산기
출력)
What is the order amount? 10
What state do you live in? Wisconsin
What county do you live in? Eau Claire
"The state tax is $0.55."
"The county tax is $0.05."
"The total tax is $0.60."
"The total is $10.60."
예제 21. 숫자에 해당하는 이름으로 바꾸기
출력)
Please enter the number of the month: 3
The name of the month is March.
#include <iostream>
#include <string>
using namespace std;
int num;
int main() {
cout << "Please enter the number of the month: ";
cin >> num;
string month = "";
switch(num){
case 1: month = "January"; break;
case 2: month = "Feburary"; break;
case 3: month = "March"; break;
case 4: month = "April"; break;
case 5: month = "May"; break;
case 6: month = "June"; break;
case 7: month = "July"; break;
case 8: month = "August"; break;
case 9: month = "September"; break;
case 10: month = "October"; break;
case 11: month = "November"; break;
case 12: month = "December"; break;
default : month = "Invalid month"; break;
}
cout << "The name of the month is " + month;
}
예제 22. 숫자 비교
세 개의 숫자를 입력 받은 다음, 먼저 세 개의 숫자가 서로 다른지를 확인아혀 같은 숫자가 있다면 프로그램을 종료시키고, 그렇지 않은 경우에는 입력한 세 개의 숫자 중 가장 큰 수를 출력시키는 프로그램을 작성하라.
출력)
Enter the first number: 1
Enter the second number: 51
Enter the third number: 2
The largeset number is 51.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> nums;
int a;
int main() {
cout << "Enter the first number: ";
cin >> a;
nums.push_back(a);
cout << "Enter the second number: ";
cin >> a;
nums.push_back(a);
cout << "Enter the third number: ";
cin >> a;
nums.push_back(a);
sort(nums.begin(), nums.end());
cout << "The largest number is " + to_string(nums[nums.size()-1]);
}
예제 23. 자동차 문제 해결
출력)
Is the car silent when you turn the key? y
Are the battery terminals corroded? n
The battery cables may be damaged.
Replace cables and try again.
#include <iostream>
#include <string>
using namespace std;
string answer;
int main() {
cout << "열쇠를 꽂고 돌렸을 때 차가 조용한가?";
cin >> answer;
if(answer == "y"){
cout <<"배터리 단자가 부식되었는가?";
cin >> answer;
if(answer == "y"){
cout <<"단자를 깨끗하게 하고 다시 시도하라";
}else{
cout <<"케이블을 교체하고 다시 시도하라";
}
}else{
cout << "차에서 달깍거리는 소리가 나는가?";
cin >> answer;
if(answer == "y"){
cout << "배터리를 교체하고 다시 시도하라";
}else{
cout << "시동이 완전히 걸리지 않는가?";
cin >> answer;
if(answer == "y"){
cout << "점화 플러그 연결 상태를 점검하라.";
}else{
cout << "엔진이 동작한 후 바로 꺼지는가?";
cin >> answer;
if(answer == "y"){
cout << "차에 연료 분사 장치가 있는가?";
cin >> answer;
if(answer == "y"){
cout << "초크가 제대로 여닫히는지 확인하라.";
}else{
cout << "서비스 센터에 의뢰하라.";
}
}else {
cout << "x";
}
}
}
}
}
정리
switch(num){
case 0: 어쩌고; break;
}
vector<int> a;
a.push_back(num);
'Computer > Coding Test' 카테고리의 다른 글
C++ 문법 기초다지기 예제 모음5 - 반복 (0) | 2024.10.24 |
---|---|
C++ 기초 문법 다지기 예제 모음4 - 함수 (0) | 2024.10.24 |
C++ 문법 기초다지기 예제 모음2 - 연산 (0) | 2024.10.23 |
C++ 문법 기초다지기 예제 모음1 - 입력, 프로세싱, 출력 (1) | 2024.10.23 |
1717: 집합의 표현 - Union-Find Tree (0) | 2024.07.22 |