繁体   English   中英

从字符串中获取系数

[英]Getting coefficients from a string

我有一个项目来编写一个程序,该程序从用户接收一个多项式字符串,直到 5 次方(例如 x^3+6x^2+9x+24)并打印出所有实数和虚数根。 系数应存储在动态数组中。

问题是从字符串中获取这些系数。 其中一个系数可以是 0(例如 2x^2-18),所以我不能使用增量从左到右存储系数,因为在这种情况下 a=2,b=-18,c 有没有价值,这是错误的。

另一个问题是系数是否为 1,因为在这种情况下,x 旁边不会写任何内容供程序读取(例如 x^2-x+14)。 另一个问题是用户是否添加了一个空格、多个空格或一个空格(例如 x ^3 +4x^ 2- 12 x + 1 3)。

我一直在考虑伪代码很长一段时间,但什么都没有想到。 我想过从左到右检测数字并读取数字并在x处停止,但是出现了第一个和第二个问题。 我想找到每个 x 然后检查它之前的数字,但是出现了第二个问题,而且我不知道用户输入的数字有多大。

这是另一个正则表达式,您可以在删除空格字符后使用它来获取系数:

(\d*)(x?\^?)(\d*)

它使用组(由方括号表示)。 每场比赛有3组:

  1. 你的系数
  2. x^n, x 或什么都没有
  3. 指数

如果 (1) 为null (例如不存在),则表示您的系数为1

如果 (2) 和 (3) 为null ,则您有最后一个没有x的数字。

如果只有 (3) 是null ,你有一个没有^nx

您可以在像这样的在线正则表达式网站上尝试一些示例,您可以在其中看到右侧的结果。

网上有很多关于如何在 C++ 中使用 Regex 的教程。

您应该标准化您的输入字符串,例如,删除所有空间然后解析系数。

让我们看看我的例子。 请根据您的情况进行更改。

#include <iostream>
#include <regex>
#include <iterator>
#include <string>
#include <vector>
#include <algorithm>

int main(int argc, char *argv[]) {

    std::string input {argv[1]};
    input.erase(remove_if(input.begin(), input.end(), isspace), input.end());
    std::cout << input  << std::endl;
    std::vector<int> coeffs;
    std::regex poly_regex(R"(\s*\+?\-?\s*\d*\s*x*\^*\s*\d*)");
    auto coeff_begin = std::sregex_iterator(input.begin(), input.end(), poly_regex);
    auto coeff_end = std::sregex_iterator();
    for (std::sregex_iterator i = coeff_begin; i != coeff_end; ++i) {
        std::smatch match = *i;
        std::string match_str = match.str();
        // std::cout << " " << match_str << "\n";
        std::size_t plus_pos = match_str.find('+');
        std::size_t minus_pos = match_str.find('-');
        std::size_t x_pos = match_str.find('x');
        if (x_pos == std::string::npos) {
            std::cout << match_str.substr(plus_pos + 1) << std::endl;            
        } else if (x_pos == 0) {
            std::cout << 1 << std::endl;
        } else if (minus_pos != std::string::npos) {
            if (x_pos - minus_pos == 1) std::cout << -1 << std::endl;
            else std::cout << match_str.substr(minus_pos, x_pos - minus_pos) << std::endl;            
        }
        else {
            std::cout << match_str.substr(plus_pos + 1, x_pos - plus_pos - 1) << std::endl;            
        }
    }
    for (auto i: coeffs) std::cout << i << " ";
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM