Quote:
Originally Posted by seanohue
How do I write an algorithm in C++? My teacher assigned us HW tonight in which we need to write an algorithm for interest (10000 at 6% yearly interest, taking out 500 a month, how much long will it take to run out (I did it by hand and got 1 3/4 years, but he wants it in code)) and then one to compute pi/4 to 6 significant digits (it says like 1 - (1/3) + (1/5) - (1/7) + (1/9)....) and the fat screw didnt teach us how to do it and it is nowhere in this book. (Sorry for the anger, this is immensly frustrating).
|
An algorithim is a way to do something, which is put in a form which a computer can understand. Akwok already covered this, but I'll give another example. Say you have 10 numbers and you wish to determine which of them is the biggest. One algorithim is to start at the first number, record it. Then go to the next number and if it is bigger than the recorded number, scratch out the recorded number and put the current number in its spot. And then continue until you get to the 10th number. That is one algorithim. Another algorithim is to split it into 2 groups of numbers. First find the biggest number in the first group using the aforementioned method. Then find the biggest number in the second group using the aforementioned. Then compare the these two numbers and see which is bigger. That is another algorithims. There are many ways to go about this task of determining which is the biggest number, some of which are easier to write, some harder, some are better for when there aren't many numbers, some for when there are very many, some require the numbers to be sorted etc.
As for computing pi/4, if it's really as you said (1 - 1/3 + 1/5 - 1/7 + 1/9...), then this is how you do it. Read it and try to understand how I did it. Also note that I do not know how to make sure it is accurate to 6 decimal places. I assume the method is to take the current result, subtract pi/4 from it, then take the absolute value of that and see if it is < 0.00000001. But I would not bet anything on that. Now, the code (adapt it to whatever language):
double currentAnswer = 1
boolean subtract = true;
int divider = 3;
int const NUMBER_OF_TIMES = x; // where x is the number of times you want to go through this
for (int i = 0; i < NUMBER_OF_TIMES; i++)
{
if (subtract == true) {
currentAnswer = currentAnswer - (1 / divider);
subtract = false;
}
else {
currentAnswer = currentAnswer + (1 / divider);
subtract = true;
}
divider = divider + 2;
}
cout << currentAnswer << endl;
BTW, if you try to copy and paste that you will likely fail since like I said I don't actually know how to calculate pi/4, so this code only works as well as the algorithim you gave in your post