Barbara Ericson, Allen B. Downey, Jason L. Wright (Editor)
Section5.2Program Development
At this point you should be able to look at complete C++ functions and tell what they do. But it may not be clear yet how to go about writing them. I am going to suggest one technique that I call incremental development.
The first step is to consider what a distance function should look like in C++. In other words, what are the inputs (parameters) and what is the output (return value).
In this case, the two points are the parameters, and it is natural to represent them using four doubles. The return value is the distance, which will have type double.
The return statement is a placekeeper so that the function will compile and return something, even though it is not the right answer. At this stage the function doesn’t do anything useful, but it is worthwhile to try compiling it so we can identify any syntax errors before we make it more complicated.
I chose these values so that the horizontal distance is 3 and the vertical distance is 4; that way, the result will be 5 (the hypotenuse of a 3-4-5 triangle). When you are testing a function, it is useful to know the right answer.
Once we have checked the syntax of the function definition, we can start adding lines of code one at a time. After each incremental change, we recompile and run the program. That way, at any point we know exactly where the error must be—in the last line we added.
doubledistance(double x1,double y1,double x2,double y2){double dx = x2 - x1;double dy = y2 - y1;
cout <<"dx is "<< dx << endl;
cout <<"dy is "<< dy << endl;return0.0;}
I added output statements that will let me check the intermediate values before proceeding. As I mentioned, I already know that they should be 3.0 and 4.0.
If you are ever unsure why a function isn’t returning what you expect it to, using cout statements at different steps in your function will help you figure it out.
When the function is finished I will remove the output statements. Code like that is called scaffolding, because it is helpful for building the program, but it is not part of the final product. Sometimes it is a good idea to keep the scaffolding around, but comment it out, just in case you need it later.
The next step in the development is to square dx and dy. We could use the pow function, but it is simpler and faster to just multiply each term by itself.
As you gain more experience programming, you might find yourself writing and debugging more than one line at a time. Nevertheless, this incremental development process can save you a lot of debugging time.
Once the program is working, you might want to remove some of the scaffolding or consolidate multiple statements into compound expressions, but only if it does not make the program difficult to read.