Why does Math.ceil return a double?
The range of double
is greater than that of long
. For example:
double x = Long.MAX_VALUE;
x = x * 1000;
x = Math.ceil(x);
What would you expect the last line to do if Math.ceil
returned long
?
Note that at very large values (positive or negative) the numbers end up being distributed very sparsely - so the next integer greater than integer x
won't be x + 1
if you see what I mean.
Java: This method must return a result type of type double
Try the following:
public class Goovy123 {
public static void main(String[] args) throws InterruptedException {
System.out.println(berekenPrijs(0));
System.out.println(berekenPrijs(1));
System.out.println(berekenPrijs(2));
System.out.println(berekenPrijs(3));
}
static public double berekenPrijs(int aantalBallen) {
if (aantalBallen == 0) {
return 0;
} else if (aantalBallen == 1) {
return 0.80;
} else if (aantalBallen <= 3 && aantalBallen >= 2) {
return 0.9 * aantalBallen * 0.80;
}
return Double.NaN;
}
}
Sample run:
0.0
0.8
1.4400000000000002
2.16
Integer or double return value
if entry.getPluggableInvWavelength() returnsd an int
the results of /100
will also be an int
If you have to have a double result, then you must store a double result.
double wavelength;
public void setWavelength(double value) {
this.wavelength = value;
}
pluggable.setWavelength(entry.getPluggableInvWavelength()/100.0);
Dividing by 100.0 is all you need to have a double result with 2 decimal places.
Why is eclipse incorrectly saying my method must return a double?
The compiler has detected that if all three if
conditions are not met, then the method would not return any value. This may not logically make sense in this case -- as either one of the three conditions must be met, but the compiler doesn't really care about this semantically.
Imagine that you're debugging the program, and when the method is called, one
is greater than two
. Then the first if
condition is not met and the execution goes to the next condition which should be true. But if while a breakpoint is suspending the execution, you change the value of one
to be less than two
using the debugger, then the second if
condition will not be met either. Eventually, this scenario leads to no condition being met.
When a return
statement is added at the end, then no matter what scenario occurs during execution, the method is guaranteed to return a value.
Double function not returning Double value?
You need to cast explicitly to double before devision.
double term(int numr, long denom) {
return ((double)numr / denom);
}
java weird double return
The reason why 'check4' is displayed 3 times is due to the fact that findClosestXupper
is being called within its self 3 times. The first time, all cases hold true, and findClosestXupper(xone, fxone);
is called. In the second call, all cases hold true again, resulting in a second call to findClosestXupper(xone, fxone);
. In the third call, the cases do not hold true, and 'check4' is printed, and then the third call returns. This causes the second call to complete its call and return its 'check4', which then returns and causes the first call to also complete and return the first 'check4'. The reason we see slightly arbitrary trailing decimal values is due to floating point precision. More on that can be found here.
Why this function returns 0 instead of a double?
Compile with a C99 or C11 compiler and read the warnings. You are using the function without prototype.
Without a prototype, pre-C99 assumes a function to return int
by default.
C99 and later, require a prototype.
Even without additional warnings enabled:
$ cat test.c
int main()
{
int i = f();
return 0;
}
int f(void)
{
return 1;
}
$ gcc -std=c11 test.c
test.c: In function ‘main’:
test.c:13:2: warning: implicit declaration of function ‘f’ [-Wimplicit-function-declaration]
int i = f();
Note that gcc will not warn if compiling -std=c90
, but will if enabling warnings -Wall
.
So, as higher()
is expected to return an int
, the value is converted to double
by the assignment (the type of c
is not changed).
And now for the funny part: undefined behaviour (UB, memorize this phrase!) due to different signature for call and implementation of the function.
What might happen is according to procedure call standard (PCS) and the application binary interface (ABI) - check Wikipedia. Briefly: higher
itself returns a double
. That is likely passed in a floating point CPU register to the caller. The caller, OTOH, expects the return value (due to the missing prototype) in an integer CPU register (which happens to hold 0
by chance).
So, as they apparently have misscommunication, you get the wrong result. Note that this is a bit speculatively and depends on the PCS/ABI. All to remember is this is UB, so anything can happen, even demons flying out of your nose.
Why use prototypes:
Well, you allready noticed, the compiler has no idea, if you call a function correctly. Even worse, it does not know, which argument types are used and which result type is returned. This is particlularily a problem, as C automatically converts some types (which you did encounter here).
As classical K&R (pre-standard) C did not have prototypes, all arguments to unknown functions were assumed int
/double
for scalar arguments on a call. The result defaults to int
. (Long time ago, I might be missing some parts; I started some coding with K&R, messed up types (exactly your problem here, but without a clean solution), etc., threw it in a corner and happily programmed in Modula-2 until some years later I tried ANSI-C).
If compiling code now, you should at least conform to (and compile for) C99, better use the current standard (C11).
How to return 2 values from a Java method?
Instead of returning an array that contains the two values or using a generic Pair
class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.
Note: A generic Pair
class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.
Example (which doesn't use really meaningful names):
final class MyResult {
private final int first;
private final int second;
public MyResult(int first, int second) {
this.first = first;
this.second = second;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
// ...
public static MyResult something() {
int number1 = 1;
int number2 = 2;
return new MyResult(number1, number2);
}
public static void main(String[] args) {
MyResult result = something();
System.out.println(result.getFirst() + result.getSecond());
}
Related Topics
How to Set Up Unit Testing for Visual Studio C++
Memory Alignment:How to Use Alignof/Alignas
What Is the Purpose of the "Final" Keyword in C++11 for Functions
What Does -Fpic Mean When Building a Shared Library
How Does a Sentinel Node Offer Benefits Over Null
What Does an Object Look Like in Memory
What Is a Good Naming Convention for Vars, Methods, etc in C++
Initialize a Vector to Zeros C++/C++11
What Is the Use of "Using Namespace Std"
Why Is a C++ Vector Called a Vector
Opengl: Glflush() VS. Glfinish()
Class Members and Explicit Stack/Heap Allocation
Difference Between Std::Function<> and a Standard Function Pointer
Different Compiler Behavior for Expression: Auto P {Make_Pointer()};