C++加减乘除计算器
多壹 人气:0#include <iostream> #include <conio.h> #include <string> void main() { char str[0xFF]; do { system("cls"); float a{}; float b{}; int count = 1; int isOperating = -1; bool isFirst = true; std::string text{ "按任意键重置,继续计算\n" }; std::cout << "------计算机------\n"; std::cout << "请输入加减乘除:"; std::cin >> str; for (int i = strlen(str) - 1; i >= 0; i--) { float* num = isFirst ? &b : &a; switch (str[i]) { case '*': isOperating = 0; break; case '/': isOperating = 1; break; case '+': isOperating = 2; break; case '-': isOperating = 3; break; } if (!isFirst&&!isdigit(str[i])&& str[i]<=127&& str[i]>=0) { isOperating = 4; text = "暂只支持正整数加减乘除,不能输入中文,其他符号或运算符\n按任意键重新输入\n"; break; } if (isOperating != -1 && count != 1 && isFirst) { isFirst = false; count = 1; if (i == 0 || i == strlen(str) - 1) { isOperating = 4; break; } continue; } *num += ((int)str[i] - 48) * count; count *= 10; } switch (isOperating) { case 0: std::cout << "结果为:" << a * b << std::endl; break; case 1: if (a == 0) text = "除数不能为0\n按任意键重置,继续计算\n"; else std::cout << "结果为:" << a / b << std::endl; break; case 2: std::cout << "结果为:" << a + b << std::endl; break; case 3: std::cout << "结果为:" << a - b << std::endl; break; default: text = text == "按任意键重置,继续计算\n" ? "错误格式,按任意键重新输入\n" : text; } std::cout << text; _getch(); } while (true); }
用string接受做太简单了,用char数组比较好玩
#include<iostream> using namespace std; int main() { double a,b; char op; cout << "enter a" << endl; cin >> a; cout << "enter operator" << endl; cin >> op; cout << "enter b" << endl; cin >> b; double result; if (op=='+') { result = a + b; } else if (op=='-') { result = a-b; } else if (op=='*') { result = a*b; } else if (op=='/'){ if (b==0){ cout << "cannot devided by 0\n"; return 0; } else{ result =a/b; } } else { cout << "invalid operator\n"; return 0; } cout << "result is " << result << endl; return 0; }
加载全部内容