开发者

Making the output of an operation to display 2 decimal points

开发者 https://www.devze.com 2023-03-20 13:22 出处:网络
Here\'s my current code: import java.util.Scanner; public class Addition { // main method begins execution of Java application

Here's my current code:

import java.util.Scanner;

public class Addition
{
    // main method begins execution of Java application
    public static void main( String args[] )
    {
       // create Scanner to obtain input from command window
       Scanner input = new Scanner( System.in );            

       int area;
       int number1;
       int number2;


       System.out.print开发者_开发问答( "Input base value =  " ); // prompt
       number1 = input.nextInt(); // read first number from user

       System.out.print( "Input height value = " ); // prompt
       number2 = input.nextInt(); // read second number from user

       area = 1/2*(number1*number2); // add numbers
       System.out.printf( "The Area of the right triangle is %d\n", area ); // display sum

    } // end method main

 } // end class Addition

I would like to make it display the decimal point when i input 5 as the first and second number. i tried replacing int area with double area but doesn't work..


If you want two digits after the decimal point, you must make area a double and use a format string of %1.2f.

Example:

System.out.printf("%1.2f\n", 78785.7);


You can check out the vast array of examples here:

Formatting Numerical Data

Hope it helps :) Cheers!


In addition to making area a double, you'll also need to make at least one of the terms in 1/2*(number1*number2) a double, or you'll only be doing int math, which won't turn out how you expect. For example:

1.0/2*(number1*number2)

In your output, you'll also have to use %f instead of %d.

0

精彩评论

暂无评论...
验证码 换一张
取 消