void MainWindow::drawFunction() { QString expression = ui->expressionEdit->text(); if (expression.isEmpty()) return; QCustomPlot *plot = ui->plotWidget; plot->addGraph(); plot->graph()->setPen(QPen(Qt::blue)); plot->graph()->setName(expression); double xMin = -10, xMax = 10, yMin = -10, yMax = 10; plot->xAxis->setRange(xMin, xMax); plot->yAxis->setRange(yMin, yMax); QVector<double> xValues, yValues; for (double x = xMin; x <= xMax; x += 0.1) { double y = calculate(expression, x); xValues.append(x); yValues.append(y); } plot->graph()->setData(xValues, yValues); plot->replot(); } void MainWindow::clearPlot() { QCustomPlot *plot = ui->plotWidget; plot->clearGraphs(); plot->replot(); }这是一段将函数输入框里的函数解析然后使用qcustomplot进行绘图的代码,帮我改进一下(变量名称不要改变),使其能够支持幂函数、对数函数、指数函数、三角函数的图像绘制
时间: 2023-12-10 10:41:17 浏览: 23
可以考虑使用 Qt 的数学库来计算不同类型的函数,然后根据函数类型进行相应的绘图。
以下是修改后的代码示例:
```cpp
void MainWindow::drawFunction() {
QString expression = ui->expressionEdit->text();
if (expression.isEmpty()) return;
QCustomPlot *plot = ui->plotWidget;
plot->addGraph();
plot->graph()->setPen(QPen(Qt::blue));
plot->graph()->setName(expression);
double xMin = -10, xMax = 10, yMin = -10, yMax = 10;
plot->xAxis->setRange(xMin, xMax);
plot->yAxis->setRange(yMin, yMax);
QVector<double> xValues, yValues;
for (double x = xMin; x <= xMax; x += 0.1) {
double y = 0;
if (expression.contains("pow")) {
// 幂函数,例如 pow(x, 2)
QStringList args = expression.split(",");
if (args.size() == 2) {
int base = args[0].mid(4).toInt();
int exponent = args[1].toInt();
y = qPow(base, exponent);
}
} else if (expression.contains("log")) {
// 对数函数,例如 log(x)
double base = M_E;
int pos = expression.indexOf("_");
if (pos > 0) {
base = expression.mid(pos + 1).toDouble();
}
y = qLn(x) / qLn(base);
} else if (expression.contains("exp")) {
// 指数函数,例如 exp(x)
y = qExp(x);
} else if (expression.contains("sin")) {
// 正弦函数,例如 sin(x)
y = qSin(x);
} else if (expression.contains("cos")) {
// 余弦函数,例如 cos(x)
y = qCos(x);
} else if (expression.contains("tan")) {
// 正切函数,例如 tan(x)
y = qTan(x);
} else {
// 表达式中未识别的函数类型
continue;
}
xValues.append(x);
yValues.append(y);
}
plot->graph()->setData(xValues, yValues);
plot->replot();
}
void MainWindow::clearPlot() {
QCustomPlot *plot = ui->plotWidget;
plot->clearGraphs();
plot->replot();
}
```
这里使用了 Qt 的数学库来计算幂函数、对数函数、指数函数、三角函数的值,并根据函数类型进行相应的绘图。注意,这里只支持了常见的函数类型,对于其他函数类型,需要根据实际需求进行扩展。