题解 | #实现简单计算器功能#
实现简单计算器功能
https://www.nowcoder.com/practice/e7c08272a4b7497fb990ce7abb1ee952
刚开始我的做法 #include <iostream> using namespace std; int main() { char str[100] = { 0 }; cin.getline(str, sizeof(str)); // write your code here...... string s(str); string arr[3]; int count = 0, tem; int i = 0; while((tem = s.find(' ', count)) != s.npos){ arr[i].assign(s, count, tem); count = tem + 1; i++; } arr[i].assign(s, count); int a, b; a = atoi(arr[1].c_str()); b = atoi(arr[2].c_str()); if(arr[0] == "add") cout<< a + b <<endl; else if(arr[0] == "sub") cout<< a - b <<endl; else if(arr[0] == "mul") cout<< a * b <<endl; else if(arr[0] == "div") if(b == 0) cout<<"Error"<<endl; else cout<<a/b<<endl; return 0; } #include <iostream> #include <cstring> #include <string> using namespace std; int main() { char str[100] = { 0 }; cin.getline(str, sizeof(str)); // write your code here...... string s(str); char * arr[30] = {str, nullptr}; int i = 0; //大佬做法: while ((arr[i] = strtok(arr[i], " ")) && ++i); int a, b; a = atoi(arr[1]); b = atoi(arr[2]); string tem(arr[0]); if(tem == "add") cout<< a + b <<endl; else if(tem == "sub") cout<< a - b <<endl; else if(tem == "mul") cout<< a * b <<endl; else if(tem == "div") if(b == 0) cout<<"Error"<<endl; else cout<<a/b<<endl; return 0; }