c语言编程 题计算器,[蓝桥杯][2017年第八届真题]小计算器 (C语言代码)

解题思路:

注意事项:

#include

using namespace std;

typedef long long LL;

int n;

string order;

string Left,Right,oper;

string Hex="10";

//任意进制转换为十进制

LL hexToTen(string num)

{

LL HEX=atoll(Hex.c_str());

LL res=0,tmp=1;

for (int i=num.size()-1;i>=0;i--){

int base;

if (num[i]>='A'&&num[i]<='Z'){

base=num[i]-'A'+10;

}

else{

base=num[i]-'0';

}

res+=tmp*base;

tmp*=HEX;

}

return res;

}

LL getResult()

{

LL a=atoll(Left.c_str());

LL b=atoll(Right.c_str());

LL c=0;

if (oper=="ADD"){

c=a+b;

}

if (oper=="SUB"){

c=a-b;

}

if (oper=="MUL"){

c=a*b;

}

if (oper=="DIV"){

c=a/b;

}

if (oper=="MOD"){

c=a%b;

}

return c;

}

//将结果转化为当前进制 ,并输出

void hexToNow(LL result)

{

if (result==0){

puts("0");

return;

}

vector v;

LL HEX=atoll(Hex.c_str());

LL t;

while (result!=0){

t=result%HEX;

if (t>=10){

v.push_back((char)('A'+t-10));

}

else{

v.push_back((char)(t+'0'));

}

result/=HEX;

}

for (int i=v.size()-1;i>=0;i--){

cout << v[i];

}

cout << endl;

}

void solveOper(string order,string num)

{

char tmp[105];

if (order=="NUM"){

if (oper==""){

sprintf(tmp,"%lld",hexToTen(num));

Left=string(tmp);

}

else{

sprintf(tmp,"%lld",hexToTen(num));

Right=string(tmp);

sprintf(tmp,"%lld",getResult());

Left=string(tmp); oper=Right="";

}

}

else if (order=="CHANGE"){

Hex=num;

}

else if (order=="EQUAL"){

hexToNow(atoll(Left.c_str()));

}

else if (order=="CLEAR"){

Left=oper=Right="";

}

else{

oper=order;

}

}

int main()

{

cin >> n;

getchar();

while (n--){

getline(cin,order);

int index=order.find(' ');

if (index < 0){

solveOper(order,"");

}

else{

solveOper(order.substr(0,index),order.substr(index+1));

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值