How to rewrite this part of code using FOR LOOP

Hello, I can't figure out how to rewrite this part of code by for loop?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
        
//Project 2



#include<iostream>
#include<math.h>
#include<fstream.h>
ifstream datain;
ofstream dataout;

using namespace std;
 int main()
 {
     float FX,X1,X2,X3,FX1,FX2,L,Y,Lambda,I;    
     float X=0,g=9.8;
     float material[13][3];
     string name[13];
     int row,col;
     
     //finding x1 x2;
     FX=1-.375*X+.028125*pow(X,2)-.0008789*pow(X,3)+.000012*pow(X,4);
     if(FX>0)
     {
           do
     {
           FX=1-.375*X+.028125*pow(X,2)-.0008789*pow(X,3)+.000012*pow(X,4);
    
            X1=X-.25;
             cout<<X<<"\n";
              X=X+.25;
              
              X2=X-.25;
     }while(X!=5&&FX>0);
     }
     else if(FX<0)
     {
          do
          {   FX=1-.375*X+.028125*pow(X,2)-.0008789*pow(X,3)+.000012*pow(X,4);
    
            X1=X-0.25;
             cout<<X<<"\n";
             X=X+.25;
             
             X2=X-.25;
     }while(X!=5&&FX<0);
     }
     else
     {X1=0;
     X2=0;
     }
     cout<<"\n Two X values are: \n";
     cout<<"X1= "<<X1<<"    X2="<<X2<<"\n\n";
     cout<<"\n\n";
     
     // finding the aquirate x1 and x2;
     
    do
    {FX1=1-.375*X1+.028125*pow(X1,2)-.0008789*pow(X1,3)+.000012*pow(X1,4);
    FX2=1-.375*X2+.028125*pow(X2,2)-.0008789*pow(X2,3)+.000012*pow(X2,4);
    X3=X2-(FX*(X1-X2))/(FX1-FX2);
    X1=X2;
    X2=X3;
}while((X3-X2)>.0010);
     system ("pause"); 
}

Last edited on
here what I am done so far, but I can't figure out how can "pick " corect value for X..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

//Project 2


#include<iostream>
#include<math.h>
using namespace std;

int main()
{
    //variables
    float start, end, inc, ans,x,y,x1,x2;
    start=0;
    end=5;
    inc=.25;

    
  cout<<"    x....."<<"         y";
    
    for(x=start;x<=end;x=x+inc)
        
        {
        y=1-0.375*x+0.028125*pow(x,2)-0.0008789*pow(x,3)+0.000012*pow(x,4);
        cout<<"\n";
        cout<<"   "<<x<<"\t__________|"<<y;
        }
        
   

   
   
   
    cout<<"\n\n";
    system("pause");
}


@zed55

The fundamental problem is that you cannot compare floating point numbers directly, so doing so in a loop condition will almost certainly fail. Use integer values in loop conditions, cast them to double inside the loop.

Google C++ floating point comparisons and have a read. Be advised that answers found on forums are not always correct.

The correct answer involves an absolute value and a comparison with a scaled epsilon value.

HTH
Topic archived. No new replies allowed.