Question:
Quick programming question?
anonymous
2013-01-21 20:06:49 UTC
This is what I need to have outputted by java

The sum of 7 and 5 is 12
The product of 6 and 3 is 18
The square of 5 if 25.0
52 divided by 3.0 is 17.333

Here is my code thus far

System.out.print("The sum of 7 and 5 is ");
System.out.print(7+5);
System.out.println();
System.out.print("The product of 6 and 3 is ");
System.out.print(6*3);
System.out.println();
System.out.print("The sqaure of 5 is ");
System.out.print(Math.pow(5,2));
System.out.println();
System.out.print("52 divided by 3.0 is ");
System.out.print(52/3.0);
I know this does what I want it to, but my question is, How do I get the 17.333? My output is 17.33333332. And I know there is probably a way of simplifying this i.e. less lines needed, but sadly I wasn't paying attention in class and I dont have my book on me to look up it up.

Thanks
Four answers:
?
2013-01-21 20:18:21 UTC
try this



System.out.printf("%.3f",52/3.0);
yunoknow?
2013-01-22 04:20:31 UTC
Just typecast it.



(int)(7+5)



This should work.



You got 17.33333 because that's what 52/3.0 is. Since 3.0 is a double when you devided the int by a double the datatype upgraded to a double. If you typecast it it will floor to 17 (though 17.33333 is the correct answer).
Kaydell
2013-01-22 04:18:13 UTC
Instead of using print() or println() you can use format() or printf() with a specifier for the rounding.



I don't know what it is exactly, but it should be on this page documenting the Formatter class in Java.



http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html
leroy
2013-01-22 09:04:16 UTC
you need to check your Decimal..here is a e.g. code



double num1 = 17.3333332 ;

DecimalFormat threeForm = new DecimalFormat threeForm("#.###");

System.out.println(Double.valueof(threeForm.format(num1)));



//My answer was 17.333

//Dont forget to import java.text.DecimalFormat

// :) hope it helps


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...