如何要求用户输入c语言的数学函数?

时间:2022-12-28 15:45:24

I am doing a university project where I have to create a numerical integration calculator. I need the user to input the integrand function to replace the double f(double x) function below so that my program can work for any 1-D integral with non-infinity limits.

我正在做一个大学项目,我必须创建一个数值积分计算器。我需要用户输入被积函数来替换下面的双f(双x)函数,以便我的程序可以用于任何具有非无穷限制的1-D积分。

Here is the code:

这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double f(double x)
{
    return x;
}

double traprule(double a, double b, double N)
{
    double h, sum, fn, fa, fb, I;

    sum = 0;
    h = (b - a) / N;

    for (int n = 1; n < N; n++)
    {
        fn = f(a + n * h);
        sum = sum + fn;
    }

    fa = f(a);
    fb = f(b);
    I = 0.5 * h * ((fa + fb) + 2 * sum);
    return I;
}

int main()
{
    scanf("%s", &f)
    double result;
    result = traprule(0, 10, 10);
    printf("%lg", result);
    return 0;
}

1 个解决方案

#1


2  

The C standard library includes nothing that would allow you to parse arbitrary mathematical expressions directly. The implementation of such an expression parser/evaluator is far outside the scope of a Stack Overflow answer, but if you are allowed to use an external library (i.e., this problem is not what your project is about), there are open source options, such as TinyExpr. You should be able to just read the user's input into a string (such as with fgets) and pass it to the library.

C标准库包含的任何内容都不允许您直接解析任意数学表达式。这样的表达式解析器/求值程序的实现远远超出了Stack Overflow答案的范围,但是如果允许使用外部库(即,这个问题不是你的项目的问题),那么有开源选项,比如TinyExpr。您应该能够将用户的输入读入字符串(例如使用fgets)并将其传递给库。

(If you are not allowed to use a library, read up on parsers and study the diagrams and source code on the linked github page, then ask a more specific question if you run into problems.)

(如果不允许使用库,请阅读解析器并研究链接github页面上的图表和源代码,如果遇到问题,请提出更具体的问题。)

#1


2  

The C standard library includes nothing that would allow you to parse arbitrary mathematical expressions directly. The implementation of such an expression parser/evaluator is far outside the scope of a Stack Overflow answer, but if you are allowed to use an external library (i.e., this problem is not what your project is about), there are open source options, such as TinyExpr. You should be able to just read the user's input into a string (such as with fgets) and pass it to the library.

C标准库包含的任何内容都不允许您直接解析任意数学表达式。这样的表达式解析器/求值程序的实现远远超出了Stack Overflow答案的范围,但是如果允许使用外部库(即,这个问题不是你的项目的问题),那么有开源选项,比如TinyExpr。您应该能够将用户的输入读入字符串(例如使用fgets)并将其传递给库。

(If you are not allowed to use a library, read up on parsers and study the diagrams and source code on the linked github page, then ask a more specific question if you run into problems.)

(如果不允许使用库,请阅读解析器并研究链接github页面上的图表和源代码,如果遇到问题,请提出更具体的问题。)