From: Randolph Wang <rywang@CS.Princeton.EDU>
Date: Tue, 23 Mar 2004 19:53:35 -0500
To: mh@princeton.edu
Cc: randy_class@CS.Princeton.EDU
Subject: Re: practice midterm question
> Hi,
>
> Thanks for your response! I was wondering if you could help on some new
> questions as well.
>
> For 2 a), why exactly does it only output 2.0? is it because the variable
> is declared as a double, but only integers are used in the Math.sqrt() so it
> rounds off to nearest tenth?
>
>
330 is an integer.
70 is an integer.
Therefore, 330/70 is done as integer arithmetic.
So the result is 4.
Math.sqrt() expects a double input.
So the system converts 4 (integer) to 4.0 (double).
The answer of Math.sqrt() is a double, which goes into the double
variable a.
>
> Also, for 2 b), is there a particular order of operation for && and || ?
> For instance if you have a && b || c, is it a && (b || c) or (a && b) || c
> ? Or do you just do it as it comes?
>
>
&& is like multiply.
|| is like addition.
So without parenthesis, x || y && z == x || (y && z)
If this is not what you want, you need to put in extra parenthesis.
BTW, for questions like this, you can simply write a small piece of
Java code and try them.
>
> And when is 'return' used? I've seen it used in the recursive functions,
> and I've seen it used in the main function to return a value from another
> function, and this was just a little confusing.
>
"return" does two things: (1) it immediately stops execution of the
current function, and (2) it returns a particular value as the answer
of the current function call to the caller. Like so:
int foo() {
return 5;
}
int bar() {
int x = foo();
}
----------------------------------------------------------------------
And (somewhat) obviously, you can have multiple "return" statements in
a function, but for any particular invocation, only one of them would
ever get executed, because as soon as one return is encounted, the
function finishes immediately so there's no chance of executing
anything else. Like so:
int foo() {
...
if (x == 0) {
return 5;
}
return 10;
}
This function returns either 5 or 10.
----------------------------------------------------------------------
Sometimes, a function is declared to have a void type so there's
nothing to return. Like so:
void foo() {
return;
}
int bar() {
foo();
}
In this case, "return" just stops the execution of the current
function and the caller takes over.
>
>
> Thanks,
>
> Michael
Re: practice midterm question / Randolph Wang