Results 1 to 8 of 8
Thread: Output a Two Decimal Value
 07172011, 11:26 AM #1Member
 Join Date
 Jul 2011
 Posts
 3
 Rep Power
 0
Output a Two Decimal Value
It's suppose to display 12.50 but instead it's displaying 0.0
Java Code:import java.io.*; public class InputOutput { public static void main(String[] args) { String base=""; String height=""; BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("Input base value = "); base = input.readLine(); System.out.print("Input height value = "); height = input.readLine(); } catch(IOException e) { System.out.print("Error"); } float area = 1/2*(Integer.parseInt(base)* Integer.parseInt(height)); System.out.println("The Area of the right triangle is "+ area); } }
 07172011, 11:41 AM #2
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 14,231
 Blog Entries
 7
 Rep Power
 24
Integer division (as in 1/2) chops of the entire fractional part of the quotient, so 1/2 == 0. Either multiply by 0.5 or do the division using floating point numbers, as in 1.0/2.0
kind regards,
JosThe only person who got everything done by Friday was Robinson Crusoe.
 07172011, 11:46 AM #3Member
 Join Date
 Jul 2011
 Posts
 3
 Rep Power
 0
But i need to use the formula 1/2*bh for computing for the area of the triangle. What should I change in the code?
 07172011, 11:48 AM #4
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 14,231
 Blog Entries
 7
 Rep Power
 24
 07172011, 11:58 AM #5Member
 Join Date
 Jul 2011
 Posts
 3
 Rep Power
 0
no, i mean i still have to use 1/2 not 0.5
 07172011, 12:09 PM #6
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 14,231
 Blog Entries
 7
 Rep Power
 24

Please reread the entire text of the 2nd post in this thread: 2nd post
 07172011, 12:24 PM #8Member
 Join Date
 Jul 2011
 Posts
 1
 Rep Power
 0
Both of these will work:
float area = (1f/2f) * (Integer.parseInt(base)* Integer.parseInt(height));
float area = (0.5f) * (Integer.parseInt(base)* Integer.parseInt(height));
The problem is (as JosAH says) is that 1/2 =0.0 (because they are assumed to be int literals) so you need to make them float literals to return 0.5 correctly.
Babbard
Similar Threads

Decimal to binary, octal to decimal
By matejm1994 in forum New To JavaReplies: 3Last Post: 12262010, 10:59 AM 
using decimal numbers
By iminhell in forum New To JavaReplies: 3Last Post: 10312010, 04:47 AM 
how to get the resultset output into an output file
By renu in forum New To JavaReplies: 0Last Post: 09302010, 08:16 PM 
Java, output string, getting correct output? HELP!
By computerboyo in forum New To JavaReplies: 2Last Post: 02262009, 12:44 AM 
Truncating decimal numbers in the output
By gbade in forum New To JavaReplies: 2Last Post: 11212008, 07:25 PM
Bookmarks