Ok, I have ripped out my hair trying to solve this. I am having problems getting
ID: 3546426 • Letter: O
Question
Ok, I have ripped out my hair trying to solve this. I am having problems getting a C++ program that I am writing to work properly. I have traced the problem to this small piece of program. Can anyone help me to figure out how to get this thing to increment correctly. Here's what I have so far:
#include <iostream> //pre-processor directs - iostream talks to screen
#include <iomanip> //pre-processor directs - string
#include <cmath> // allows math functions
using namespace std;
const int size=100;
int main ( void )
{
double x[size], y[size];
double L = 2.0, I = 7.29167e-8, E = 2.05e+11;
int N = 10, W = 125;
for (int i=0;i<L;i++) //initiates, defines and sets counter
x[i]=(i*(L/N)); //initiates the first value of the array
cout<<" This program has calculated the deflection of the beam";
cout<<" from the information supplied by you."<<endl;
cout<<" Distance from end of beam: x(m) "<<" Deflection: d(m)"; //prints column headers to screen
cout<<" ------------------------------------------------------------"<<endl;
for (int i=0;i<L;i++) //initiates, defines and sets counter
y[i]=(-W/(6*E*I))*(pow(x[i],3)-3*pow(L,2)*x[i]+2*pow(L,3)); //calculates beam deflection
for (int i=0;i<N;i++)
//initiates, defines and sets counter
cout<<setiosflags(ios::scientific)<<setprecision(2)<<setw(10)
<<x[i]<<setprecision(2)<<setw(35)<<y[i]<<endl;//prints values in arrays to screen
cout<<endl;
system("pause");
return 0;
}
This is what my result should be.
Distance from end of beam: x(m) Deflection: d(m)
0.000E+00 -2.230E-02
2.000E-01 -1.897E-02
4.000E-01 -1.570E-02
6.000E-01 -1.257E-02
8.000E-01 -9.633E-03
1.000E+00 -6.969E-03
1.200E+00 -4.638E-03
1.400E+00 -2.709E-03
1.600E+00 -1.249E-03
1.800E+00 -3.233E-04
2.000E+00 0.000E+00
I get nothing like it. Any help would be appreciated.
Explanation / Answer
The problem is contained in your for loops.
for (int i=0;i<L;i++) //initiates, defines and sets counter
x[i]=(i*(L/N)); //initiates the first value of the array
and
for (int i=0;i<L;i++) //initiates, defines and sets counter
y[i]=(-W/(6*E*I))*(pow(x[i],3)-3*pow(L,2)*x[i]+2*pow(L,3)); //calculates beam deflection
Since L is 2.0 it stops after 2, which is the reason why the first and second rows of the table is correct while the rest is all a hot mess. Just change the i<L to i<=N in both of those for loops and it will produce the exact table you want it to, with a bit of rounding error(change your setprecision to 3 instead to fix). You'll need to change the printing for loop to i<=N as well if you want the very last line.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.