Hi i'm following a tutorial and video i found online , im trying to make a template to preform a numerical integration of a function where a user can decide which form of integration to preform, im trying to keep it to one file as not to use headers and not use massive ammounts of loops , the code for the first integration works fine on its own but when i run it through a template i get the wrong answer and the same value 1.9147e-307 for every input what am i doing wrong?
#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
re开发者_开发问答turn 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
is never assigned a value. That would account for your 1.9147e-307.
Did you intend
ans = MyCalc.MC();
before the cout
?
Also
INTG(T a, T b,T n){
INTG::a = a;
INTG::b = b;
}
Is better described as
INTG(T a, T b, T n):a(a),b(b),n(n) {}
Initializing instead of assigning, and remembering n.
So the calculation sequence would be
INTG<double> MyCalc(a,b,n);
ans = MyCalc.MC();
if (OP = 1) {
...should be...
if (OP == 1) {
精彩评论