#include <array> #include <stdexcept> using namespace std; string calculator(int op, int a, int b) { switch (op) { case 1: return to_string(a+b); case 2: return to_string(a-b); case 3: return to_string(a*b); case 4: { if (b!= 0) return to_string(a/b); else return "Invalid Input!"; } case 5: return to_string(a%b); default: return "Invalid Input!"; } }
#include <string>- #include <array>
- #include <stdexcept>
template <typename T>std::string calculator(int op, T x, T y) {try {std::array<std::function<T(T, T)>,5> ops{{std::plus<>{},std::minus<>{},std::multiplies<>{},[&](T x, T y) {if (y!=0) return x/y; else throw std::range_error{"Illegal divide by 0"};},[&](T x, T y) {if (y!=0) return x%y; else throw std::range_error{"Illegal modulus % 0"};},}};return std::to_string(ops.at(op-1)(x,y)); // 'at()' will throw !!} catch (const std::out_of_range& e) {return "Invalid Input!";} catch (const std::range_error& e) {return "Invalid Input!";}}- using namespace std;
- string calculator(int op, int a, int b)
- {
- switch (op)
- {
- case 1:
- return to_string(a+b);
- case 2:
- return to_string(a-b);
- case 3:
- return to_string(a*b);
- case 4:
- {
- if (b!= 0)
- return to_string(a/b);
- else
- return "Invalid Input!";
- }
- case 5:
- return to_string(a%b);
- default:
- return "Invalid Input!";
- }
- }
#include <functional> #include <string> using namespace std; string calculator(int op, int x, int y) { static array<std::function<int(int, int)>, 5> ops{ plus<int>(), minus<int>(), multiplies<int>(), divides<int>(), modulus<int>(), }; if (op < 1 || op > 5 || (!y && (op == 4 || op == 5))) return "Invalid Input!"; return std::to_string(ops[op-1](x, y)); }
- #include <functional>
- #include <string>
std::string calculator(int op, int x, int y) {static std::array<std::function<int(int, int)>, 5> ops{std::plus<int>(),std::minus<int>(),std::multiplies<int>(),std::divides<int>(),std::modulus<int>(),- using namespace std;
- string calculator(int op, int x, int y) {
- static array<std::function<int(int, int)>, 5> ops{
- plus<int>(),
- minus<int>(),
- multiplies<int>(),
- divides<int>(),
- modulus<int>(),
- };
- if (op < 1 || op > 5 || (!y && (op == 4 || op == 5))) return "Invalid Input!";
- return std::to_string(ops[op-1](x, y));
- }
unsigned long long div2(unsigned long long a){ unsigned long long ans = 0, i; for (i = 1; i <= a; i++) { if (i % 2 != 0){ continue; } else { ans++; } } return ans; }
- unsigned long long div2(unsigned long long a){
- unsigned long long ans = 0, i;
- for (i = 1; i <= a; i++) {
if (i % 2){- if (i % 2 != 0){
- continue;
- } else {
- ans++;
- }
- }
- return ans;
- }