-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
미해결
std::cin 계산기 숙제 제출
20.10.18 04:17 작성 조회수 164
0
입출력은 잘 되는데 어딘가 꾸리꾸리한 기분이 듭니다
특히 for문 부분 인데요,
for문을 이렇게 구성해도 되는걸까 궁금하여 제출겸 질문글 올려봅니다
제 생각엔 while 반복문 안에서 추가적인 연산을 해서 안좋다는 느낌이 드는것 같습니다
선생님과 다른분들의 의견이 궁금합니다.
https://onlinegdb.com/S1ZHXT_vD
#include <iostream>
// ########## std::cin 더 잘 써보기 ##########
// 사용자가 의도하지 않은대로 입력하였을때
// ignore(), clear(), fail()
// ########## TODO ##########
// TODO 1: more operators *, / etc.
// TODO 2: if, else 를 switch, case문을 이용하여 바꿔보시오
int GetInt()
{
while (true)
{
std::cout << "Enter an integer Number : ";
int x;
std::cin >> x;
const short Short_Max = 32767;
if (std::cin.fail()) // fail is true
{
std::cin.clear();
std::cin.ignore(Short_Max, '\n');
std::cout << "Invalid number, Please try again" << std::endl;
}
else // !fail is false
{
std::cin.ignore(Short_Max, '\n');
return x;
}
}
}
char GetOperator()
{
const char Operation[4]{ '+','-','*','/' };
// Operation[0] == '+'
// Operation[1] == '-'
// Operation[2] == '*'
// Operation[3] == '/'
while (true)
{
std::cout << "Enter an Operator(+, -, *, /) : ";
char op;
std::cin >> op;
const short Short_Max = 32767;
std::cin.ignore(Short_Max, '\n');
int i = 0;
for (; i < 4; ++i) // 이 부분..?
{
if (op == Operation[i])
return op;
}
if (op != Operation[i]) // not Operation
std::cout << "## Invalid operator, Please try again" << std::endl;
}
}
void PrintResult(int x, char op, int y)
{
switch ((char)op)
{
case((char)'+'):
std::cout << " Result = " << x + y << std::endl;
break;
case((char)'-'):
std::cout << " Result = " << x - y << std::endl;
break;
case((char)'*'):
std::cout << " Result = " << x * y << std::endl;
break;
case((char)'/'):
std::cout << " Result = " << x / y << std::endl;
break;
default:
std::cout << "## Not Found Operator" << std::endl;
break;
}
}
int main()
{
int Input;
do
{
system("cls");
int x = GetInt();
char op = GetOperator();
int y = GetInt();
PrintResult(x, op, y);
std::cout << "Again? (Replay : 0) : ";
std::cin >> Input;
} while (Input == 0);
return 0;
}
답변을 작성해보세요.
1
Hello Yeo
2020.10.19
안녕하세요?
상황에 따라 다르겠지만 너무 세세한 것에 신경쓰시기보다는
알고리즘을 통해 이득을 취하시는 것이 도움이 된다고 생각합니다.
4개 중 매칭이 되는 것을 찾을 때 제안하신 방법보다 딱히 더 좋은게 떠오르진 않는군요.
답변 1