您好,我正在关注我在网上找到的教程和视频,我正在尝试制作一个模板来执行函数的数值积分,用户可以在其中决定执行哪种形式的积分,我正在尝试将其保存到一个文件中由于不使用 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/