Ok so I wrote a program for Euler's method of approximation (new programmer, first program) and I created a sort of loop that should end, but goes on much longer than it should. I don't know why. For example, I input the parameters 1 and 1 for initial x and y, and 2 iterations, and 2 as my end result x, and it tried to do the loop hundreds of times, when it should only have needed to do it twice. Odd.
#include "stdafx.h"
#include <iostream>
// Welcome to Euler's Method of Approximation
using namespace std;
int x, n, inx, finx, d, y, yprime, dy;
/*
n is number of iterations
d is your change in x for each step
*/
void math_function() { yprime = 2 * x; } // This is your derivative/math function, you'll need to change this for new cases
void get_newx() //this updates the x value for the next step
{
x = x + d;
}
void get_newy()
{
y = y + dy; //this updates the y value for the next step
}
void loop()
{
math_function(); // y prime function (m)
dy = yprime*d; // getting your change in y (delta y)
get_newy(); // getting the resultant y
get_newx(); // getting the resultant x to use next time
}
void results()
{
if (x == finx) { cout << y; }
else
{
loop();
results();
}
}
int main()
{
cout << "How many iterations do you want?" << endl;
cin >> n;
cout << "What is the initial x value?" << endl;
cin >> x;
cout << "What is your initial y value?" << endl;
cin >> y;
cout << "What will your final x value be?" << endl;
cin >> finx;
d = (finx - x) / n;
results();
return 0;
}
Aucun commentaire:
Enregistrer un commentaire