2

I'm finding a logarithm of value 1 which is equal to 0 not 0.0. When user enter any point values then it give exact answer. But the problem is Which Value Does Not Consist in points it give the answer of those value in points.I try parsing and Typecasting but nothing happen.Is there a function in Java which can Stop This.
This is my Code.

public class New { public static void main(String[] args) { Scanner s = new Scanner(System.in); double num = 0; double result; System.out.print("Value:"); num = s.nextDouble(); result = Math.log(num); System.out.print("Answer:"+result); } } 

Compiler Output:

Value:1 Answer:0.0 
5
  • What happens when you switch double num = 0; to int num = 0; ? Commented May 29, 2015 at 17:23
  • log(1) does indeed equal 0 Commented May 29, 2015 at 17:24
  • What exactly is the problem? What is the expected output? Commented May 29, 2015 at 17:24
  • i do it but when any point values come it give error Commented May 29, 2015 at 17:24
  • 1
    @Philipp Wendler i want output 0 not 0.0 in double datatype Commented May 29, 2015 at 17:26

3 Answers 3

1

The 0.0 is how the double value representing 0 is printed by default. Also, the Math.log method returns a double. 0.0 is equal to the number 0. The logarithm, any positive base, of 1 is 0.

If you'd like not to print the decimal point if the result is an integer, then test if it's an integer.

if (result == (int) result) { System.out.println((int) result); } else { System.out.println(result); } 
Sign up to request clarification or add additional context in comments.

5 Comments

(result == (int) result) will return true for any exact integer representation, ie. double 0, 1, or 2, but NOT double 3, since it can't be represented exactly. Just a caveat; it's not a perfect method for checking integer-ness.
@ShotgunNinja While one should generally be careful of double values that can't be represented exactly, 3 isn't one of them. 3 can be represented exactly as a double.
Oh derp, I was thinking of simple fractions, not simple integers...
@rgettman Is it good way to use if else or typecast in this.Does Java has any function that can do this job.
Because you want 2 different output formats based on whether it's an integer, using if/else is good. You can use Math.floor and test whether the floor of the number is equal to the number. It's best to use the cast here. It's possible to use a DecimalFormat to control the output also.
1
System.out.print("Answer:" + (result == 0.0 ? "0" : result)); 

Comments

1

This isn't because of the internal representation or the value, or what it is equivalent to; this is because of how the double value 0 is displayed when rendered to a String (ie. by the code "Answer:"+result). The value under the hood returned from Math.log(1) is the double representation of a IEEE 754 positive zero, which for all intents and purposes is equivalent to the integer constant 0.

Comments