-2

For homework we've been assigned I am trying to use a for loop in c++ but apparently I don't understand how they work that well. Here's the code:

{
   double L,W,E,A,H,B,I;
   L=6.5;
   W=2;
   E=450;
   A=2.8;
   H=0.5;
   B=0.8;
 

   I= (1/12)*B*(H*H*H);
   for ( double x = 0; 0 <= x <= 2.8; x + 0.1)
    { 
       double F,S,G;
        F= -((W)*(x*x))/(24*E*I);
        S= (6*(A*A))-(4*A*x)+(x*x);
        G= F*S;
        cout << G;
   }

Basically what I'm trying to do is make a loop where x increases in increments of 0.1 until it hits 2.8, outputting the values for G along the way. But right now it gives me an infinite output of nan. Is there something I'm missing?

pm100
  • 48,078
  • 23
  • 82
  • 145
  • 3
    I think [this question](https://stackoverflow.com/questions/8889522/is-4-y-1-a-valid-statement-in-c-how-do-you-evaluate-it-if-so) might help you out. Essentially, `(0 <= x <= 2.8)` isn't computing `(0 <= x) && (x <= 2.8)`. It's computing `((0 <= x) <= 2.8)`. Since `0 <= x` is `true`, the expression is equivalent to `true <= 2.8`, which after `bool` to numeric promotion means `1 <= 2.8`, which is also `true`, so your loop never ends. – Nathan Pierson Mar 29 '22 at 04:26
  • 2
    Also, `x + 0.1` will add to `x` but it'll discard the result. You want to do `x += 0.1` instead; that will actually update `x`'s value. – Didier Mar 29 '22 at 04:28
  • 1
    [How to format code blocks](https://stackoverflow.com/editing-help) – 273K Mar 29 '22 at 04:29
  • Admittedly the duplicate is a different language, but the problem is the same. The condition in your loop is always true because of that syntax misunderstanding, which of course causes the endless loop. – Yunnosch Mar 29 '22 at 06:18

1 Answers1

0

Your loop test and increment are wrong, you need

for ( double x = 0; x <= 2.8; x += 0.1)
pm100
  • 48,078
  • 23
  • 82
  • 145