0
double pi=22/7; system.out.println(pi);..why does this code snippets display 3.0 instead of pi value....
4 Respuestas
+ 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.
+ 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).
+ 1
public class Program {
public static void main(String[] args) {
double pi = (double) 22/7;
System.out.println(pi);
}
}
output : 3.14159265358
0
wow..I get it now..Thanks man🙌