0

double pi=22/7; system.out.println(pi);..why does this code snippets display 3.0 instead of pi value....

5th Aug 2016, 11:57 PM
Ridwan
Ridwan - avatar
4 Réponses
+ 3
It is integer division. Because 22 and 7 are integer so the result of 22/7 is 3. But variable pi is double, so there is type casting from integer to double, 3 to 3.0 To fix, change division number type to double or do type casting. e.g. double pi = 22.0/7; double pi = 22/7.0; or type casting double pi = (double)22/7; double pi = 22/(double)7; be careful, if cast like (double)(22/7), this will return 3.0 as (22/7) which is integer devision done first.
6th Aug 2016, 12:44 AM
WPimpong
WPimpong - avatar
+ 2
becoz logic was very simple.intger divide by integer is always integer.so even if u write this arithmetic operation u will get output in the form of integer only.so for that u have to used type-casting( float,double,.........//any data type depend on the user).
20th Sep 2016, 6:18 PM
Pranit Bhoir
Pranit Bhoir - avatar
+ 1
public class Program { public static void main(String[] args) { double pi = (double) 22/7; System.out.println(pi); } } output : 3.14159265358
6th Aug 2016, 1:12 PM
Mohammad Reza Karimi
Mohammad Reza Karimi - avatar
0
wow..I get it now..Thanks man🙌
6th Aug 2016, 8:59 AM
Ridwan
Ridwan - avatar