-2

/**
 * Write a description of class GUI here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */

import java.util.*;
public class GUI
{
    // instance variables - replace the example below with your own
    public static void main(String [] args){
        
        Scanner r = new Scanner(System.in);
        
        int x;
        int y;
        int z;
        
        System.out.println("x");
        
        x = r.nextInt();
        
        System.out.println("y");
        
        y = r.nextInt();
        
        System.out.println("z");
        
        z = r.nextInt();
       
        double t = (x+y+z)/3;
        
        System.out.println("result " + t);
    }
}

Hello, above is my code.

I purposely made it int x,y,z to test the program.

When I input for example (when running the program) :$x = 1, 1, 3$ it rounds the answer always! Why is this?

Amad27
  • 151
  • 1
  • 1
  • 8

1 Answers1

2

This is an example of Java's integer division, which must always return another integer. It truncates any decimal result. This occurs even though the result is assigned to a double.

Use a double literal when dividing to force floating-point division.

double t = (x+y+z)/3.0;
rgettman
  • 176,041
  • 30
  • 275
  • 357