How can i get (22.22) as a output. I tried using double data type but I'm getting 22.0 Can anyone tell me the reason ?
8 Answers
New Answer1/23/2022 5:52:24 AM
Davinder Kumar8 Answers
New Answerimabhiiiiii🥱 You're first doing integer division then implicitly casting the result to double that's why the output is 11.0 (Also as per Java naming convention only class names starts with capital letters) As Simba pointed out you can either change the parameters type to double or you can just divide by 3.0 both will give you the same answer 11.6666666666 If you want to format the output to 2 decimal places then Java has quite a few ways. Here is a site that teaches how to format decimals in 7 different ways. Choose as per your need. https://java2blog.com/format-double-to-2-decimal-places-java/
Here, you defined your return type as double not parameters(numbers) that you used to calculate the average. double Number1, double Number2....
It should print as you expected. double x = 2222; double y = 100; System.out.println(x/y); How did you do that?
class Calculator { public double findAverage(int Number1,int Number2,int Number3){ double avg=(Number1+Number2+Number3)/3; //(35/3) return avg; } } class Tester { public static void main(String args[]) { Calculator calculator = new Calculator(); System.out.println(calculator.findAverage(12,8,15)); //35 //expected output is 11.67 } }
Here, you define your return type as double not parameters that you used to the average. answer 11.66666 here is a useful link for you : https://java2blog.com/format-double-to-2-decimal-places-java/
Sololearn Inc.
535 Mission Street, Suite 1591Send us a message