gpt4 book ai didi

Java 浮点除法的显式类型转换

转载 作者:行者123 更新时间:2023-12-02 03:12:11 24 4
gpt4 key购买 nike

我不确定是否在选项 4(除法)中对浮点除法使用显式类型转换。我需要一些帮助来理解什么是浮点除法。

我必须使用整数来存储 2 个操作数,使用 double 来存储结果。您必须对选项 4 中的浮点除法使用显式类型转换。还可以使用 switch 语句来处理菜单选项。每次计算后

import java.util.Scanner;

public class SimpleCalculator
{
//-----------------------------------------------------------------
// Calculates two integers
// using values entered by the user.
//-----------------------------------------------------------------
public static void main(String[] args)
{
//Variables
final int ADDITION = 1,SUBTRACTION = 2, MULTIPLICATION = 3,DIVISION = 4, EXIT = 5;
int num1 = 0, num2 = 0, choice = 0;
double dblNum1, dblNum2, result;
String equation = "";

do
{
//Processing
equation = "";
Scanner scan = new Scanner(System.in);
System.out.println("Choose from the following: ");
System.out.println("1. Add 2 integers");
System.out.println("2. Subtract 2 integers");
System.out.println("3. Multiply 2 integers");
System.out.println("4. Divide 2 integers");
System.out.println("5. Exit");
System.out.print("Enter choice: ");

choice = scan.nextInt();

if(choice < 5 && choice > 0)//keeps program from asking for two numbers if exiting
{
System.out.print("Enter first integer: ");
num1 = scan.nextInt();

System.out.print("Enter second integer: ");
num2 = scan.nextInt();
}

//switch for operations
switch (choice)
{
case ADDITION:
result = num1 + num2;
equation = ((num1) + " + " + (num2) + " = "+ result);
break;

case SUBTRACTION:
result = num1 - num2;
equation = ((num1) + " - " + (num2) + " = "+ result);
break;

case MULTIPLICATION:
result = num1 * num2;
equation = ((num1) + " * " + (num2) + " = "+ result);
break;

case DIVISION:
if(num2 == 0)//when denominator becomes zero
{
System.out.println("DIVISION NOT POSSIBLE");
break;
}
dblNum1 = num1;//convert int to double
dblNum2 = num2;
result = dblNum1/dblNum2;
equation = ((num1) + "/" + (num2) + " = "+ result);
break;

case EXIT:
System.exit(0);
break;

default:
System.out.println("YOU HAVE ENTERED AN INCORRECT CHOICE");
}
//Output
System.out.println(equation);
System.out.println();
}while(choice != EXIT);
}
}

最佳答案

不,这不是明确的类型转换。你会想使用这样的东西:

result = ((double) num1) / ((double) num2);

实际上,由于 / 运算符的扩展规则,您只需要这些显式转换之一,但同时拥有两者也没有坏处。事实上,由于强制转换运算符 () 的优先级高于除法运算符 /,因此您可以将其写为:

result = (double) num1 / num2;

它结合了分子的显式转换和分母的隐式转换。

关于Java 浮点除法的显式类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40873114/

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