即可计算整形又可计算浮点型的二目计算器
思路:
将计算器部分封装成一个模板函数,之后输入两个实数及运算符,并判断输入的数是否为小数。将输入的变量初始化为字符串,并遍历两个字符串,若字符串中有字符'.'便将字符串转化为浮点型数据,否则将字符串转化为整形变量,处理完输入的数据后将数据作为参数传入函数并将返回值用cout输出
代码实现:
//
// Created by ashichoco on 2020/11/18.
//
#include<iostream>
#include<cstdlib>
using i32 = int32_t;
using i64 = int64_t;
class Solution {
public:
template<class T>
auto addTwoNum(T a, char c, T b) {
switch(c) {
case '+': {
auto temp = a + b;
return temp;
}
case '-': {
auto temp = a - b;
return temp;
}
case '*': {
auto temp = a * b;
return temp;
}
case '/': {
auto temp = a / b;
return temp;
}
default: {
std::cout << "errer\n";
exit(1);
}
}
}
}run;
i32 main() {
std::string a,b;
char c;
std::cin >> a;
std::cin.sync();
std::cin >> c;
std::cin.sync();
std::cin >> b;
bool flag = false;
if (c == '/')
flag = true;
for (auto x:a)
if(x == '.') flag = true;
for (auto x:b)
if(x == '.') flag = true;
if(flag){
auto f1 = atof(a.c_str());
auto f2 = atof(b.c_str());
std::cout << run.addTwoNum(f1, c, f2) << '\n';
return 0;
}
auto i1 = atoi(a.c_str());
auto i2 = atoi(b.c_str());
std::cout << run.addTwoNum(i1, c, i2) << '\n';
return 0;
}