hi,

it gives me output 0Code:`double a=1/2;`

System.out.println(a);

how to make it 0.5?

regards

dhilip

Printable View

- 03-26-2012, 02:05 PMnoobplushow to calculate division in java
hi,

Code:`double a=1/2;`

System.out.println(a);

how to make it 0.5?

regards

dhilip - 03-26-2012, 02:16 PMKevinWorkmanRe: how to calculate division in java
1 and 2 are both ints. An int divided by an int will give you an int. Variables that are ints do not have decimal places.

You can cast one or both of the values to a double before doing the division, or you could use double literals (1.0 instead of 1, for example). - 03-26-2012, 02:18 PMgauravfzdRe: how to calculate division in java
in your code you are doing a integer division and then automatic type promotion is performed.So u will always get 1/2 as 0.

Use it like this:

float a = 1f; float b = 2f;

float c = a/b;

*you can use double instead of float - 03-26-2012, 02:19 PMnoobplusRe: how to calculate division in java
- 03-26-2012, 02:20 PMnoobplusRe: how to calculate division in java
- 09-07-2016, 08:51 AMprakashsanjayRe: how to calculate division in java
package com.corejava.sonu;

import java.util.Scanner;

public class Division {

public static void main(String args[]){

float x,y,z;

System.out.println("Enter the two integers value");

Scanner in =new Scanner(System.in);

x=in.nextInt();

y=in.nextInt();

z=x/y;

System.out.println("Division of two integers="+z);

}

}

**try this simple example for division using float - 09-07-2016, 11:27 AMSurfManRe: how to calculate division in java