C++ template help, using a template for integrations - c++

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
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 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) {

Related

Recursive (sum of even numbers from 2 to (2 times n) ex: input : n=6, output : 2+4+6

Can anyone fix this code to make it right?
I think it's almost right but the last number is correct number but followed by random number.
#include <iostream>
using namespace std;
int jumlah(int a, int b){
if(a*2==b){
cout<<b;
}else{
cout<<b<<"+";
cout<<jumlah(a, b+2);
}
}
int main(){
int a, b;
b=2;
cin>>a;
jumlah(a, b);
return 0;
}
Your function never returns anything, so printing the result of the recursion is undefined.
Remove the result from the function and recurse without printing.
void jumlah(int a, int b){
if(a*2==b){
cout<<b;
}else{
cout<<b<<"+";
jumlah(a, b+2);
}
}
Your code has undefined behavior since the function does not return anything.
Change it to:
int jumlah(int a, int b){
if ( a*2 == b){
return b;
}
cout << b << "+";
return jumlah(a, b+2);
}
and change the call in main to:
cout << jumlah(a, b);

Hello, This simple C++ script pops out an error at line 11. Does anybody know how to fix it?

Description
This code is intended to find a spanner index (i) when dealing with
Splines/NURBS basis functions based on a knot vector (U), a choosen knot (u), the degree of the desired curve (p) and the number of basis funcions (n). The algorithm was taken from the NURBS Book by Piegl and Tiller. The error, I guess, is in the way I declared variable U. Thaks in advanced!
code
# include <iostream>
using namespace std;
int n=3;
int p=2;
double u=5/2;
int U[11]={0,0,0,1,2,3,4,4,5,5,5};
int FindSpan(n,p,u,U) /* an error in this line */
{
if (u==U[n+1]) return (n);
low=p; high=n+1;
mid=(low+high)/2
while(u<U[mid] || u>=U[mid+1])
{
if (u<U[mid]) high=mid;
else low=mid;
mid=(low+high)/2
}
return (mid);
}
You have forgotten some semicolons and types!
here is the correct code:
#include <iostream>
using namespace std;
int n=3;
int p=2;
double u=5/2;
int U[11]={0,0,0,1,2,3,4,4,5,5,5};
int FindSpan(int n, int p, int u, int U[])
{
if (u==U[n+1]) return (n);
int low=p, high=n+1;
int mid=(low+high)/2;
while(u<U[mid] || u>=U[mid+1])
{
if (u<U[mid]) high=mid;
else low=mid;
mid=(low+high)/2;
}
return (mid);
}
int main() {
cout << FindSpan(n, p, u, U);
return 0;
}

Why can't i execute this code in C++ with vectors implemented in class and functions?

So i have a school project and i'm trying to execute this code which solves a quadratic equation using as many c++ objects and learned things. the problem is i want to save the a,b and c in a vector and then use them but i can't just pull this off. can someone tell me how can i fix my code?
Ps. the cout-s and variable's names are in my native language so hope it doesn't bother you.
Thanks in advance!!!
#include <iostream>
#include <cmath>
#include<vector>
using namespace std
;class ekuacioni{
private:
int v [3];
public: void rrenjet(vector<double> &v)
{double x1,x2,rrenjadall,a,b,c;
a=v[0];
b=v[1];
c=v[2];
rrenjadall = sqrt(dallor(v));
x1= (-b + rrenjadall )/(2*a);
x2 = (- b-rrenjadall )/(2*a);
cout<<"Ekuacioni ka dy rrenje te ndryshme te cilat jane";
cout<<"x1= "<<x1<<endl;
cout<<"x2 ="<<x2<<endl;
}
public :void rrenja(vector<double> &v)
{
double x,a,b,c;
a=v[0];
b=v[1];
c=v[2];
x = -b/(2*a);
cout<<"Rrenjet jane te barabarta, x1=x2= "<<x<<endl;
}
public: double dallor( const vector<double>& v)
{
double x,a,b,c;
a=v[0];
b=v[1];
c=v[2];
return (b * b) - (4 *a *c);
}
}
;
int main() {
class ekuacioni e;
double koef [3];
cout<<"Vendosni koeficientet a,b dhe c te ekuacionit:\n";
for (int i=0;i<2;i++)
cin>>koef[i];
double dallor= e.dallor(koef);
if(dallor<0)
{cout<<"ekuacioni nuk ka rrenje reale si zgjidhje te tij."<<endl;
}
else
if (dallor==0)
{e.rrenja(koef);
}
else
{e.rrenjet(koef);
}
return 0;
}
Try this:
std::vector<double> koef;
double k1, k2, k3;
cin >> k1 >> k2 >> k3;
koef.push_back(k1);
koef.push_back(k2);
koef.push_back(k3);
There are other possibilities for loading a vector from an input source.
There is no need for the array koef. I have made it into a std::vector so it can be passed to your other functions.

Why it doesn't show me the greatest common divison?

When i try to start the program it doesn't work and doesn't show me any error. Why?
#include <iostream>
using namespace std;
int main()
{
unsigned a,b;
cout<<"a=";
cin>>a;
cout<<"b=";
cin>>b;
{
while(a!=b)
{
if(a>b)
(a==a-b);
else
(b==b-a);
}
}
cout<<"cmmdc=",a;
return 0;
}
Replace a==a-b with a=a-b.
Replace b==b-a with b=b-a.
The operator == is comparison, it doesn't modify its arguments. The operator = is assignment, it modifies its left argument to the value of its right argument.
Replace cout<<"cmmdc=",a with cout<<"cmmdc="<<a, otherwise a won't be printed.
Even after changing the ==s to =s, you'll get an infinite loop if any but not both of a and b is 0. To avoid that, use this loop instead:
while (b != 0) {
const unsigned olda = a;
a = b;
b = olda % b;
}
// GCD is now in a.
It is the simplest way to find gcd of two numbers :
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a,b;
cout<<"a = ";
cin>>a;
cout<<"b = ";
cin>>b;
cout<<"GCD = " << __gcd(a,b);
}

Unexpected result by sqrt() in quadratic formula using <math.h>

This is the task i was given
Your task is to create a class named equation which will have the data members a, b and c which are the coefficients
of the quadratic equation. The class will have two more data members namely proot and nroot which stand for the
positive root and negative root of the equation. Suppose that variables a, b and c are integers. Where proot and nroot
are floats.
- Construct the class objects by using a nullary constructor.
- Then design a friend function which will determine the proot and nroot of the equation.
- Create another friend function which will display the values of proot and nroot.
I have a couple of questions
I tried to declare "a" as an integer and take its square root it was giving an error saying that "More than one instances of sqrt match the argument list". Same thing worked when i declared "a" as double and type-casted into integer. Why is is so?
the output should be
-1
-1.5
but my output is entirely different. What am i doing Wrong?
My professor told me that to make a function friend of a class we have to write its prototype in the class. Prototype does not include "&" but if i dont write it the program does not work
enter code here
#include <iostream>
#include <math.h>
using namespace std;
class Equation
{
friend void Roots (Equation & );
friend void Display (Equation &);
int a;
int b;
int c;
float proot;
float nroot;
public:
Equation ()
{
a=0;
b=0;
c=0;
proot=0;
nroot=0;
}
Equation (int _a, int _b, int _c)
{
a=_a;
b=_b;
c=_c;
}
};
void Roots (Equation &obj1)
{
double a;
int determinant;
a=(obj1.b^2)-(4*obj1.a * obj1.c);
if (a>-1)
determinant=int(sqrt(a));
else
{
cout<<"Determinant returns an imaginary number; solution not possible\n";
exit (0);
}
obj1.proot= (-obj1.b + determinant)/2*obj1.a;
obj1.nroot= (-obj1.b - determinant)/2*obj1.a;
}
void Display (Equation &obj1)
{
cout<<"Value of positive root : "<<obj1.proot<<endl;
cout<<"Value of negative root : "<<obj1.nroot<<endl;
}
void main ()
{
int a,b,c;
cout<<"Calculate Quadratic Equation"<<endl<<"Enter A : ";
cin>>a;
cout<<"Enter B : ";
cin>>b;
cout<<"Enter C ";
cin>>c;
Equation obj(a,b,c);
Display (obj);
Display (obj);
}
a=(obj1.b^2)-(4*obj1.a * obj1.c);
The ^ operator in C++ is a bitwise XOR, so obj1.b^2 part calculates the XOR of obj1.b and the bit pattern 000...10. That is definitely not what you want here.
The power function in C++ is pow, so you square that by doing pow(obj1.b, 2), also if you're working with C++ it would be better to include the header as cmath and not math.h.
EDIT: You also never call Roots() to calculate anything:
Equation obj(a,b,c);
Display (obj);
Here you construct your equation and immediately try to show its result, without first calling Roots(obj). That will at least calculate an answer but is still wrong because there seems to be a mistake in your calculation.
You also need parenthesis around 2 * obj1.a in your calculation. Try with and without them and see the difference!
Calculate Quadratic Equation
Enter A : 10
Enter B : 10
Enter C 2
Value of positive root : -0.276393
Value of negative root : -0.723607
And this is correct. Although you apparently expect the two roots to have different signs, that is not necessarily going to be the case.
Instead of
obj1.b^2
try
pow(obj1.b, 2)
^ is doing a XOR operation - probably not what you had in mind.
You also never seem to call your Roots function. You need something like:
Equation obj(a,b,c);
Roots(obj);
Display (obj);
You are getting big numbers returned, because when you call the Equation (int _a, int _b, int _c) constructor, proot and nroot are left uninitialized. You are then returning them at the end, because you never call the Roots function.
As an example of how to create useful friend functions:
#include <iostream>
#include <cmath>
class Equation
{
public:
Equation () : m_a(0), m_b(0), m_c(0), m_proot(0), m_nroot(0)
{
}
Equation (int a, int b, int c) : m_a(a), m_b(b), m_c(c), m_proot(0, false), m_nroot(0, false)
{
}
private:
// these would be better as floats or doubles, but your requirement appears to want them to be ints. You'll need to cast them when doing division operations.
int m_a;
int m_b;
int m_c;
// std::optional would be more useful, but it was removed from the last C++14 draft
std::pair<float, bool> m_proot;
std::pair<float, bool> m_nroot;
void Calculate()
{
// do your actual calculations here
// note that you will need to set the m_proot.second and m_nroot.second values to true if they are valid
// also note that ^ is not a power operation; you need to use std::pow for that
}
// this friend function is useful
friend std::ostream& operator<<(std::ostream&, const Equation&);
// this one is created just to meet the requirements of the assignment
friend void CalculateRoots(Equation&);
};
std::ostream& operator<<(std::ostream& os, const Equation& e)
{
std::cout << "Roots of (" << e.m_a << ")x^2 + (" << e.m_b << ")x + " << e.m_c << ": "
if (m_nroot.second || m_proot.second)
{
std::cout << "(";
if (m_nroot.second)
{
std::cout << m_nroot.first << ", ";
}
if (m_proot.second)
{
std::cout << m_proot.first;
}
std::cout << ")" << std::endl;
}
else
{
std::cout << "No real roots" << std::endl;
}
return os;
}
// must be friend function to call private member function Calculate
void CalculateRoots(Equation &obj1)
{
obj1.Calculate();
}
// does not need to be a friend function - using operator<< overload (which is a friend function itself)
void DisplayRoots(Equation &obj1)
{
std::cout << obj1;
}
int main ()
{
int a,b,c;
cout<<"Calculate Quadratic Equation"<<endl<<"Enter A : ";
cin>>a;
cout<<"Enter B : ";
cin>>b;
cout<<"Enter C ";
cin>>c;
Equation obj(a,b,c);
CalculateRoots(obj);
DisplayRoots(obj);
}
This gives you the required friend functions from the assignment's description while at least pushing you closer to a better design.
Ok guys so i changed the data type of variables from
int a;
int b;
int c;
to
float a;
float b;
float c;
because it was giving warning about conversions and data loss and also changed the statement where proot and nroot are calculated from
obj1.proot= (-obj1.b + determinant)/2*obj1.a;
obj1.nroot= (-obj1.b - determinant)/2*obj1.a;
to
obj1.proot= (-obj1.b + determinant)/(2*obj1.a);
obj1.nroot= (-obj1.b - determinant)/(2*obj1.a);
Now it is working as expected...Producing correct reusult! :)