C++ 模板帮助,使用模板进行集成

标签 c++ templates

您好,我正在关注我在网上找到的教程和视频,我正在尝试制作一个模板来执行函数的数值积分,用户可以在其中决定执行哪种形式的积分,我正在尝试将其保存到一个文件中由于不使用 header 并且不使用大量循环,第一次集成的代码本身运行良好但是当我通过模板运行它时我得到了错误的答案并且每个输入的相同值 1.9147e-307 是什么我做错了吗?

#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include<conio.h>

using namespace std;

//declared function
double F(double X)
{
   double f;

   f = (X*X);
   return f;
};

double unifRand()
{
    return rand() / double(RAND_MAX);
};

template<typename T> class INTG{
    private:
        T a;
        T b;
        T n;
    public:
        INTG(T a, T b,T n){
            INTG::a = a;
            INTG::b = b;
        }

        ~INTG(){}

        T MC() {
            // some code

            return ans;}

        T SIMPC(){ // Simpson integration code here
            return a+b+n;
        }
};

int main() {
    double a,b,mc,simp,ans;
    int OP,n;
    cout<<"Enter 1 for Monte Carlo Integration , Enter 2 for Composite Simpson Integration, enter 3 for trapezoidal int...."<<endl;
    cin>>OP;
    clock_t start = clock();


    if (OP == 1) {
        cout<<"Enter lower limit of integration"<<endl;
        cin>>a;
        cout<<"Enter upper limit of integration"<<endl;
        cin>>b;
        cout<<"Enter number of iterations"<<endl;
        cin>>n;
        ans = INTG<double>::MC(a, b, n);
        INTG<double> MyCalc(a,b,n);

        cout<< ans <<endl;

        //mc =  INTG::MC(a, b, n);
        getch();
    }
}

最佳答案

ans 永远不会被赋值。那将占您的 1.9147e-307。

你有没有想过

ans = MyCalc.MC();

cout 之前 ?

还有

INTG(T a, T b,T n){
    INTG::a = a;
    INTG::b = b;
}

最好描述为

INTG(T a, T b, T n):a(a),b(b),n(n) {}

初始化而不是赋值,并记住n。

所以计算顺序是

INTG<double> MyCalc(a,b,n);
ans = MyCalc.MC();

关于C++ 模板帮助,使用模板进行集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7573658/

相关文章:

c++ - Rcpp:在不导出 C++ 函数的情况下在 R 中调用 C++ 函数

c++ - "Read"没有命名类型

c++ - 为什么编译器不能解析 std::function 参数的重载?

c++ - 为什么我们首先使用原始指针?之前不使用 RAII

c++ - 有没有办法检测混合类型和非类型的任意模板类?

c++ - 在 C++ 中初始化静态 std::map<int, unique_ptr<int>>

C++ 模板在参数中指定类型

c++ - 将数据放在类声明中?

c++ - 调用函数,如果有,否则忽略

C++ 将方法指针作为模板参数传递