0

I'm writing a program for my computer science class and I was having an issue with an equation. It wasn't until I started breaking the code up until I realized that all my doubles are being rounded down. For instance:

public static void test(){
    double var = 4/3;
    System.out.println(var);
}

This will print "1.0" to the console. I have commented out everything else in my code aside from the main method, which only calls this. Please help

SamH
  • 203
  • 1
  • 2
  • 13

1 Answers1

2

You are performing integer division in Java, which must always result in another int, even if later assigned to a double.

To force floating-point division, use double literals:

double var = 4.0/3.0;

Only one needs to have the .0 on it. Or, you can cast one of them to a double to the same effect:

double var = (double) 4 / 3;

Another option: Place a d suffix on one or both literals:

double var = 4d / 3d;
rgettman
  • 176,041
  • 30
  • 275
  • 357