mercredi 29 mars 2017

How to successfully get out of this do-while loop?

This code was smooth sailing until i SPECIFICALLY include the IF-STATEMENT containing a BREAK inside the DO-WHILE LOOP which SHOULD report a math error if fv1 = 0 (for anything divided by zero is undefined). However, unexpected results were printed. Please help me guys on my loop!

Off topic: I am a beginner, literally started from scratch, and by that i mean "Hello World" program. Big thanks to you'll for all the help. This site will save my grades this semester. hehe

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

const double R = 0.082054;
double f(double a,double b,double P,double T,double v);
double f(double a,double b,double P,double T,double v)
{
    double q =P*pow(v,3)-(P*b+R*T)*pow(v,2)+a*v-a*b;
    return q;
}
double fPrime(double a,double b,double P,double T,double v);
double fPrime(double a,double b,double P,double T,double v)
{
    double s =3*P*pow(v,2)-2*(P*b+R*T)*pow(v,1)+a;
    return s;
}
int main()
{
//INPUT STAGE!
cout << "Use gas constant, R: " << R << endl;

double a,b,P,T,Tc;
cout << "\nUse test value, a: ";
cin >> a;
cout << "\nUse test value, b: ";
cin >> b;
cout << "\nUse pressure, P (atm): ";
cin >> P;
cout << "\nUse absolute temperature, T (K): ";
cin >> T;

double v,v1=0,fv,fv1,N,e;
int iteration = 0;
cout << "\nUse initial guess for molal volume, v: ";
cin >> v;
cout << "\nUse maximum number of iterations, N: ";
cin >> N;
cout << "\nUse tolerance, e: ";
cin >> e;
cout << "\n";

do
{
    v = v1;
    fv = f(a,b,P,T,v);
    fv1 = fPrime(a,b,P,T,v);
    if (fv1=0)
    {
       cout << "Math Error";
       break;
    }
    v1 = v-(fv/fv1);
    cout << iteration+1 << setw(12) << v << setw(16) << v1 << setw(16) << abs(v1-v) << endl;
    iteration++;
}
while(iteration<N && abs(v1-v)>e);

return 0;
}

Aucun commentaire:

Enregistrer un commentaire