如何划分两个浮点数并得到一个整数

时间:2016-02-21 18:48:33

标签: java

我有两个浮点数变量,我希望除法作为整数返回。我尝试了一些东西,例如Math.Round()并将它乘以1,然后除以1,我似乎无法使它工作。

  import java.util.Scanner;

  public class Calculator
  {
     public static void main (String[] args)
     {

        float firstNumber;
        float secondNumber;
        char operator;
        float answer;
        float answerRemainder;
        Scanner input = new Scanner (System.in);


        System.out.print("Enter your first number");
        firstNumber = input.nextInt();
        System.out.print("Enter the operator (s for subtraction, a for addition, m for multiplication, d for division, r for division with a remainder))\n");
        operator = input.next().charAt(0);
        while (operator != 's' && operator != 'a' && operator != 'm' && operator != 'd' && operator != 'r')

        {
           System.out.print("\nYou have entered an incorrect character. Enter the operator (s for subtraction, a for addition, m for multiplication, d for division, r for division with a remainder)\n");
           operator = input.next().charAt(0);
        }

        System.out.print("Enter your second number");
        secondNumber = input.nextInt();

        if (operator == 's')

        {
           System.out.print(firstNumber +" - "+secondNumber+" = "+(firstNumber - secondNumber));
        }

        else if (operator == 'a')

        {
           System.out.print(firstNumber +" + "+secondNumber+" = "+(firstNumber + secondNumber));
        }

        else if (operator == 'm')

        {
           System.out.print(firstNumber+" * "+secondNumber+" = "+(firstNumber * secondNumber));
        }      

        else if (operator == 'd')

        {
           System.out.print(firstNumber+" / "+secondNumber+" = "+(firstNumber / secondNumber));
        }

        else if (operator == 'r')

        {
            answerRemainder = (firstNumber / secondNumber);
            System.out.print(firstNumber+" / "+secondNumber+" = "+(answerRemainder)+" with a remainder of "+(firstNumber % secondNumber));
        }
     }
  }

所以我想要最后一行" answerRemainder"是一个整数

2 个答案:

答案 0 :(得分:1)

您可以将您的部门转为int,如answerRemainder = (int) (firstNumber / secondNumber);

然而,正如问题评论所指出的那样,做到这一点会导致精确度下降。

如果没有任何演员,firstNumber = 3.4fsecondNumber = 1.2ffirstNumber / secondNumber的结果将为2.8333333

使用强制转换,结果为2.0,因为int是一个没有精度的数字,结果被截断并且精度被丢弃。

使用ceilingMath.ceil)向上舍入结果,结果将向上舍入,您将获得之后的整数 2.83333333.0

使用floorMath.floor)向下舍入结果,结果将向下舍入,您将获得之前的整数 2.83333332.0

注意:两个变量上的f'值是必要的,因为没有它,默认情况下,Java会将值解释为double

答案 1 :(得分:0)

Float  float_variable = (float) fistNumber/(float) secondNumber;

  answerRemainder =  Math.round(float_variable);