PAT 1060. Are They Equal

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.

Input Specification:

Each input file contains one test case which gives three numbers N, A and B, where N (<100) is the number of significant digits, and A and B are the two float numbers to be compared. Each float number is non-negative, no greater than 10100, and that its total digit number is less than 100.

Output Specification:

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.

Sample Input 1:
3 12300 12358.9
Sample Output 1:
YES 0.123*10^5
Sample Input 2:
3 120 128
Sample Output 2:
NO 0.120*10^3 0.128*10^3

代码分析

这道题首先是考有效数字的表达,在自己进行测试检验是要注意输入数据是小数的情况,最后一个测试点输入数据是0.000和00.0000的情况,给出下面几组测试数据:
3 12300 12358.9
YES 0.123*10^5


1 12300 12358.9
YES 0.1*10^5


1 1.2300 1.23589
YES 0.1*10^1


5 1.2300 1.23589
NO 0.12300*10^1 0.12358*10^1


4 0.01234 0.012345
YES 0.1234*10^-1


5 0.01234 0.012345
NO 0.12340*10^-1 0.12345*10^-1


5 0.1234 0.12345
NO 0.12340*10^0 0.12345*10^0


0 0.11 0
YES 0.*10^0或者YES 0.0*10^0,都可以AC,测试点应该没有这个例子


1 0.1 0
NO 0.1*10^0 0.0*10^0


1 0.0 0.1
NO 0.0*10^0 0.1*10^0


1 0.0 0.000
YES 0.0*10^0


1 00.0 0.000
YES 0.0*10^0


4 00.0 0.000
YES 0.0000*10^0


5 00.0 0.000
YES 0.00000*10^0


1 05.0 5.000
YES 0.5*10^1


1 00.01 0.010
YES 0.1*10^-1
#include<iostream>
#include<algorithm> 
using namespace std;
int main(){
	string a,b;
	int n,t1,t2;
	cin>>n>>a>>b;
    auto it=find(a.begin(),a.end(),'.');
    if(it!=a.end()){
	  t1=-(a.end()-1-it);
	  a.erase(it); 
	}
    else t1=0;
    int i;
    for(i=0;i<a.size();i++){
    	if(a[i]!='0') break;
	}
    a=a.substr(i,a.size()-i);
    it=find(b.begin(),b.end(),'.');
    if(it!=b.end()){
       t2=-(b.end()-1-it);
	   b.erase(it);
	}
    else t2=0;
    for(i=0;i<b.size();i++)
        if(b[i]!='0') break;
    b=b.substr(i,b.size()-i);
    t1+=a.size();   t2+=b.size();
    if(a=="")   t1=0;
    if(b=="")   t2=0;
	if(a.size()<n)  a.insert(a.end(),n-a.size(),'0');
	if(b.size()<n)  b.insert(b.end(),n-b.size(),'0');
	if(t1==t2&&a.substr(0,n)==b.substr(0,n))
           cout<<"YES 0."<<a.substr(0,n)<<"*10^"<<t1<<endl;
       else
           cout<<"NO 0."<<a.substr(0,n)<<"*10^"<<t1<<" 0."<<b.substr(0,n)<<"*10^"<<t2;
}
posted @ 2018-01-27 11:43  A-Little-Nut  阅读(208)  评论(0编辑  收藏  举报