[백준 5355] 화성 수학 (C#, C++) - soo:bak
작성일 :
문제 링크
설명
화성에서는 세 가지 연산자를 사용합니다. @는 3을 곱하고, %는 5를 더하고, #은 7을 뺍니다. 초기 숫자와 연산자들이 주어질 때 연산자를 순서대로 적용한 결과를 구하는 문제입니다.
접근법
각 줄에서 첫 번째 값을 숫자로 읽고, 이후 나오는 연산자들을 하나씩 적용합니다. 결과를 소수 둘째 자리까지 출력합니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
class Program {
static void Main() {
var t = int.Parse(Console.ReadLine()!);
for (var i = 0; i < t; i++) {
var tokens = Console.ReadLine()!.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var x = double.Parse(tokens[0]);
for (var j = 1; j < tokens.Length; j++) {
switch (tokens[j][0]) {
case '@': x *= 3; break;
case '%': x += 5; break;
case '#': x -= 7; break;
}
}
Console.WriteLine(x.ToString("F2"));
}
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t; cin >> t;
cout.setf(ios::fixed);
cout << setprecision(2);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
while (t--) {
string line; getline(cin, line);
stringstream ss(line);
double x; ss >> x;
char op;
while (ss >> op) {
if (op == '@') x *= 3;
else if (op == '%') x += 5;
else if (op == '#') x -= 7;
}
cout << x << "\n";
}
return 0;
}