如何在询问时允许用户以e ^ x或sqrt(x)的形式输入数字,而不是仅以数字形式输入数字?谢谢。
通常,这是一个解析问题。确切地说,在这两种形式的情况下,简单的解决方案可能是这样的:
string input;
getline(cin, input);
if (input[0] == 'e' && input[1] == '^') {
int num = atoi(input.substr(2).c_str()); // probably better to use stringstreams here
cout << exp(num) << endl;
} else if (input.substr(0, 5) == "sqrt(" && input[input.size() - 1] == ')') {
int num = atoi(input.substr(5, input.size() - 6).c_str());
cout << sqrt(num) << endl;
} else {
cout << "error" << endl;
}
没有测试,但应该大致正确。如果您需要处理更多的细微差别的案例或不仅仅是这两种情况,则必须进行一些更复杂的解析。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句