Mark Louie
Mark Louie

Reputation: 9

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.

#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;
}

Upvotes: 0

Views: 58

Answers (2)

peedurrr
peedurrr

Reputation: 197

The break statement ends execution of the nearest enclosing loop or conditional statement in which it appears -

And by the way you're assigning 0 to fv1.

use

if (fv1 == 0)

or

if (0 == fv1)

Upvotes: 2

Umair Mohammad
Umair Mohammad

Reputation: 4635

Try changing if condition from fv1=0 to fv1==0 This is assignment operator= whereas this is comparing operator ==

Upvotes: 2

Related Questions