[prog] C++
Mary
mary-linuxchix at puzzling.org
Sat Dec 13 12:49:34 EST 2003
On Fri, Dec 12, 2003, wolf wrote:
> I'm trying to teach myself a bit of C++ following along with a book,
> the sample asks to have three numbers entered in via the screen that
> print back the sum, average, product, largest, and smallest of the
> numbers. I think I have it working for the first three (sum, average,
> and product) but I'm having trouble trying to figure out how to make
> it select the largest and smallest of the three numbers. Would anyone
> know how to do this? Here's what I've come up with so far that seems
> to return the correct responses. I'm at the very beginning part of
> being a beginner : ) Thanks : )
When solving these kinds of problems as a beginner, it's sometimes worth
thinking "OK, well, how would *I* do this?"
This might not be so helpful for three numbers (because the answer might
come out as something like "I'd look at them and pick the smallest"),
but how would you, as a person, find the smallest of 100 numbers given
to you on 100 cards.
One solution for the smallest of three numbers is something like this:
Compare the first number with the second number and take the
smallest of the two.
Compare that number with the third number and take the smallest of
the two.
One thing you should aim for (only as an exercise at this point) is
reasonable generalisability -- that is, a solution for all the cases.
You might not be able to do the code just yet, but you should think
about how to express the steps in English.
Think about it for 100 numbers. You have 100 numbers on cards in a pile,
find the smallest. What would you do?
I'd do something like this:
Compare the first and second cards and take the smaller one.
Compare that smaller one with the third card, again take the smaller
one.
Compare that smaller one with the fourth card, again take the
smaller one.
etc until...
Compare that smaller one with the hundredth card, again take the
smaller one.
The smaller one is the smallest one we were looking for.
So you can see that our solution for three numbers is easily
generalisable to one hundred numbers (you might want to check the
solution on paper until you're happy that there are no holes in this
solution -- you may find yourself doing that a fair bit with these kinds
of exercises).
-Mary
More information about the Programming
mailing list