这是作业: 编写一个读取两个double值作为输入的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值,但我不知道有任何其他方法来执行此任务。
谢谢!
答案 0 :(得分:2)
您需要使用一种称为强制转换的操作,以明确缩小从double
到int
的类型:
ProductofInt = (int)(ValueA * ValueB);
此外,看看你的代码,我会建议一些改进点:
Question12
。camelCase
,例如productAsDouble
。此外,“as”这个词比“of”更有意义 - 你正在把它作为一个double / int表示产品并代表它,而不是采用特定int或double的产品(你的因子/除数/被除数)是总是双打)为了便于阅读,您应该尽可能将变量声明为 late 。不是在顶部声明ProductOfDouble
然后再设置它,而是在同一时间声明并设置它:
double ProductofDouble = ValueA * ValueB;
答案 1 :(得分:1)
这是java检测你正在做什么,并认为这可能是你的错误 - int
不像double
那样具体。
要修复它,请使用强制转换:
ProductofInt = (int)(ValueA * ValueB);
QuotientofInt = (int)(ValueA / ValueB);
答案 2 :(得分:0)
你使用Double计算int
结果,double比int更精确,所以你失去了精度。你需要做的是通过执行以下操作将变量从double转换为int
double a;
a=(int) b;