0
public class Test { 

public static void main(String[] args) { 

int test = 1; 

System.out.println((double)(Math.pow(test/++test, 2)));

} 

0.0 is printed to the screen. Why? Why is the cast not working as expected?

If test is declared this way...

double test = 1; 

I get what I expect to print... 0.25.

Why?

I am new to programming and I'm playing around. Reading some of the documentation at this level is next to useless.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • 2
    The cast happens too late. You have already written `(int) 1/ (int) 2` and produced `(int) 0`. Casting `0` to a `double` does not recover the truncated data. – Boris the Spider Apr 02 '17 at 07:14

1 Answers1

0

You are doing integer division. SO change the line to

System.out.println((Math.pow(test/(double)++test, 2)));

to do double division

Ed Heal
  • 59,252
  • 17
  • 87
  • 127