If a machine can save only 3 significant digits, the float numbers 12300 and 12358.9 are considered equal since they are both saved as 0.123*105 with simple chopping. Now given the number of significant digits on a machine and two float numbers, you are supposed to tell if they are treated equal in that machine. 输入描述: Each input file contains one test case which gives three numbers N, A and B, where N ( 输出描述: For each test case, print in a line "YES" if the two numbers are treated equal, and then the number in the standard form "0.d1...dN*10^k" (d1>0 unless the number is 0); or "NO" if they are not treated equal, and then the two numbers in their standard form. All the terms must be separated by a space, with no extra space at the end of a line.Note: Simple chopping is assumed without rounding. 输入例子: 3 12300 12358.9 输出例子: YES 0.123*10^5
import java.util.Scanner;
import java.math.BigDecimal;
public class AreTheyEqual {
public static void main(String[] args) {
int num1, num2;
Scanner scan0 = new Scanner(System.in);
int numwei = Integer.parseInt(scan0.nextLine());
Scanner scan1 = new Scanner(System.in);
float f1 = Float.parseFloat(scan1.nextLine());
String str1 = String.valueOf(f1);
if (str1.indexOf(".") >= 0) {
int idx1 = str1.lastIndexOf(".");
String strNum1 = str1.substring(0, idx1);
num1 = strNum1.length();
}else {
num1 = str1.length();
}
BigDecimal b1 = new BigDecimal(f1/Math.pow(10,num1));
float re1 =
b1.setScale(numwei,BigDecimal.ROUND_HALF_UP).floatValue();
Scanner scan2 = new Scanner(System.in);
float f2 = Float.parseFloat(scan2.nextLine());
String str2 = String.valueOf(f2);
if (str2.indexOf(".") >= 0) {
int idx2 = str2.lastIndexOf(".");
String strNum2 = str2.substring(0, idx2);
num2 = strNum2.length();
}else {
num2 = str2.length();
}
float r1 = (float)((f1 - f1 % Math.pow(10,numwei)) /
Math.pow(10,numwei));
float r2 = (float)((f2 - f2 % Math.pow(10,numwei)) /
Math.pow(10,numwei));
if ( r1 == r2 ) {
System.out.println("true "+ re1 +
"*10^"+ num1 );
}
else
System.out.println("false");
System.exit(0);
}
}