2014-09-18 46 views
2

這裏是作業: 編寫一個讀取兩個double值作爲輸入的java程序。您的程序需要使用Scanner類來讀取這兩個值。有了這兩個值,您的程序需要輸出以下內容: 該產品作爲一個雙倍產品,將第一個值乘以第二個產品的第二個 的商(作爲雙倍),第一個值除以第二個產品INT,由第二 商第一值乘以作爲int,由第二雙和詮釋博士。 java

這裏將第一值的的是我的代碼:

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值,但我不知道有任何其他方式來完成這個任務。

謝謝!

+4

您可以通過鑄造雙爲int規避錯誤:''INT整數=(INT)originalDouble''。這會將其舍入到最接近的整數。它不會爲您自動執行,因爲這是一個經常犯的錯誤,所以需要確定程序員是否想要將其捨棄。另請注意,Java中的慣例是讓變量名以小寫字母開頭。 – Ghostkeeper 2014-09-18 23:46:20

回答

2

您將需要使用某種類型的操作稱爲鑄造,明確類型從doubleint

ProductofInt = (int)(ValueA * ValueB); 

此外,看着你的代碼,我會建議幾個改進點:

  • 類名應該是PascalCase,而不是Captialized_And_Underscored。所以,你的班級名稱會更可行Question12
  • 變量名應該是camelCase,例如productAsDouble。此外,「as」這個詞比「of」更有意義 - 你將產品作爲一個double/int來表示,而不是使用特定的整數或雙精度的產品(你的因素/除數/被分紅是總是雙打)
  • 爲了提高可讀性,您應該聲明變量爲。相反,在頂部宣佈ProductOfDouble再後來就設置它的聲明並同時設置:

    double ProductofDouble = ValueA * ValueB; 
    
1

這是java的檢測,你在做什麼,在想它可能是一個錯誤的部分 - int s不是特定於double s。

爲了解決這個問題,使用強制:

ProductofInt = (int)(ValueA * ValueB); 
QuotientofInt = (int)(ValueA/ValueB); 
+0

@hexafraction修復您所指的缺失括號。 – Pokechu22 2014-09-18 23:50:00

0

您使用雙來計算int結果,雙比INT更精確,所以你失去精度。你需要做的是通過做從雙投的變量爲int以下 double a; a=(int) b;