[英]Count number of pairs of two numbers less than or equal to N such that Sum of the digits of numbers of pair is Prime
[英]Check if the two numbers are equal to n significant digits
我想出了代碼的主要部分,但我無法弄清楚如何獲取它所以它只會讀取差異,直到用戶輸入的多少小數點。 那么我將如何獲取用戶輸入(將輸入第三個數字)並找出前兩個數字是否等於該小數點。 該程序的目標是檢查這兩個數字是否等於n(用戶輸入的數字)有效數字。
樣本輸入:5.124 5.125 2
樣本輸出:差值= .001,數字等於2位小數
import java.util.Scanner;
public class Equal {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
String diff="diffrence =";
double num1;
double num2;
double num3;
double calc;
while(input.hasNext()){
num1 = Double.parseDouble(input.next());
num2 = Double.parseDouble(input.next());
num3 = Double.parseDouble(input.next());
calc = Math.abs(num1-num2);
System.out.printf("%s %.10f", diff, calc);
}
}
}
這是一個普通雙打的例子和junit測試用例。 希望這可以幫助。
public boolean doublesSameNumberOfDecimalPlaces(double x,double y,int numberOfDecimals){
x = (long)(x * Math.pow(10, numberOfDecimals));
y = (long)(y * Math.pow(10, numberOfDecimals));
return x==y;
}
@Test
public void TestDoublesSameNumberOfDecimalPlaces(){
double x = 3.141593;
double y = 3.14159265359;
assertTrue(doublesSameNumberOfDecimalPlaces(x,y,0));
assertTrue(doublesSameNumberOfDecimalPlaces(x,y,1));
assertTrue(doublesSameNumberOfDecimalPlaces(x,y,2));
assertTrue(doublesSameNumberOfDecimalPlaces(x,y,3));
assertTrue(doublesSameNumberOfDecimalPlaces(x,y,4));
assertTrue(doublesSameNumberOfDecimalPlaces(x,y,5));
assertFalse(doublesSameNumberOfDecimalPlaces(x,y,6));
}
使用BigDecimal
的好方法:
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Scanner;
public class Equal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String num1;
String num2;
int num3;
while (input.hasNext()) {
// First number
num1 = input.next();
// Second number
num2 = input.next();
// Number of significant figures
num3 = Integer.parseInt(input.next());
MathContext mc = new MathContext(num3, RoundingMode.HALF_UP);
BigDecimal bdNum1 = new BigDecimal(num1, mc);
BigDecimal bdNum2 = new BigDecimal(num2, mc);
System.out.println(bdNum1.equals(bdNum2));
}
input.close();
}
}
根據您的具體需求,您可能想要使用RoundingMode
。
樣本輸入:
1.2345678
1.2345679
7
樣本輸出:
true
樣本輸入:
0.123
0.124
3
樣本輸出:
false
請注意,在特殊情況下,行為可能與預期不符,如:
輸入:
0.10000
0.1000
8
輸出:
false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.