【发布时间】:2014-09-18 23:43:16
【问题描述】:
这是作业: 编写一个读取两个双精度值作为输入的 java 程序。您的程序将需要使用 Scanner 类来读取这两个值。使用这两个值,您的程序需要输出以下内容: 将第一个值乘以第二个值的乘积,作为双精度值 将第一个值除以第二个值的商,作为双精度数 第一个值乘以第二个值的乘积,作为 int 第一个值除以第二个值的商,以 int 形式表示
这是我的代码:
import java.util.Scanner;
public class Question_12 {
public static void main(String[] args) {
double ProductofDouble;
double QuotientofDouble;
int ProductofInt;
int QuotientofInt;
double ValueA;
double ValueB;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter Value A: ");
ValueA = keyboard.nextDouble();
System.out.println("Enter Value B: ");
ValueB = keyboard.nextDouble();
//calc product as double
ProductofDouble = ValueA * ValueB;
//calc quotient as double
QuotientofDouble = ValueA / ValueB;
//calc product as int
ProductofInt = ValueA * ValueB;
//calc quotient as int
QuotientofInt = ValueA / ValueB;
System.out.println("The product of Value A and Value B as a double is: " + ProductofDouble);
System.out.println("The quotient of Value A and Value B as a double is: " + QuotientofDouble);
System.out.println("The product of Value A and Value B as an int is: " + ProductofInt);
System.out.println("The quotient of Value A and Value B as an int is: " + QuotientofInt);
} }
The Error:
2 errors found:
File: /Users/gcaruso/Documents/CISS 110/Module 3/Question_12.java [line: 26]
Error: /Users/gcaruso/Documents/CISS 110/Module 3/Question_12.java:26: possible loss of precision
found : double
required: int
File: /Users/gcaruso/Documents/CISS 110/Module 3/Question_12.java [line: 28]
Error: /Users/gcaruso/Documents/CISS 110/Module 3/Question_12.java:28: possible loss of precision
found : double
required: int
我知道您不应该在 int 中使用双精度值,但我不知道有任何其他方法可以执行此分配。
谢谢!
【问题讨论】:
-
您可以通过将 double 转换为 int 来规避该错误:
int integer = (int)originalDouble。这会将其向下舍入到最接近的整数。它不会自动为您执行此操作,因为这是一个经常犯的错误,因此需要确保程序员想要将其舍入。另请注意,Java 中的约定是变量名以小写字母开头。