Code:
//----------------------------------------
y = scale(x, 2);
//y is what is returned from scale using x and the power of 2
rounded_x = (int) (x + .5);
//and now I'm unsure
x = (double) scale(x, -2);
//----------------------------------------
It's good that you're stepping it through, but I think you need to be more concrete: write it down.
It looks like you're doing the right thing in your head, but when it comes to writing it down, you're making simple avoidable coding mistakes. If you have the steps actually written down (algorithm), transcribing them into code makes mistakes a little more obvious, especially for the kind of mistakes you're making.
For example, in this:
Code:
y = scale(x, 2);
//y is what is returned from scale using x and the power of 2
The comment isn't telling you anything you don't know by reading the code. Comments shouldn't paraphrase code, they should explain code. Code tells you
what happens. Comments tell you
why it happens.
An example of a useless comment:
This is useless because anyone who knows the language well enough to read the source is going to know that "x++" means "increment x". Either the comment shouldn't be there at all, because the code is obvious, or the comment should explain why the relatively simple action of incrementing x needs to be commented upon.
Now, going back to your code... Yes, y is the returned value. So how about giving an example in the comment:
Code:
// Example: if x is 12.347, y is 1234.7
// Example: if x is 0.841, y is 84.1
Now the reader has some specific examples that illustrate exactly what happens.
Next, consider what your next line of code is doing:
Code:
rounded_x = (int) (x + .5);
Do you not see any problem with this? Look carefully at exactly what variables are being used. Read the examples in the comments immediately above this line of code. Notice anything?
And why no comments about what rounded_x holds? Again, comments should either explain or illustrate what the code does. Saying "rounded_x receives the integer value of x plus .5" would merely paraphrase the code. Add a meaningful comment here, and it might show the mistake.
And your third line:
Code:
x = (double) scale(x, -2);
Do you see any problem with this, which might be similar to a problem in one of the lines above it?