gpt4 book ai didi

java - 如何除以两个 float 并得到一个整数

转载 作者:行者123 更新时间:2023-12-01 10:21:56 27 4
gpt4 key购买 nike

我有两个都是 float 的变量,我希望除法以整数形式返回。我尝试了一些方法,例如 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”是一个整数

最佳答案

您可以将除法转换为 int,例如 answerRemainder = (int) (firstNumber/secondaryNumber);

尽管如此,正如问题评论中指出的那样,执行上述操作将导致精度损失。

在没有任何转换的情况下,如果 firstNumber = 3.4fsecondNumber = 1.2ffirstNumber/secondaryNumber 的结果将为 2.8333333.

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

使用 ceiling 将结果向上舍入(Math.ceil),结果将向上舍入,您将在之后得到整数2.8333333,其中将是 3.0

使用 floor 将结果向下舍入(Math.floor),结果将向下舍入,您将得到之前 2.8333333 的整数,其中将是 2.0

注意:两个变量值上的 f 是必需的,因为如果没有它,默认情况下 Java 会将这些值解释为 double .

关于java - 如何除以两个 float 并得到一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35540388/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com