【算法笔记】A1060 Are They Equal

时间:2024-04-30 13:59:38
1060 Are They Equal (25 分)

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 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 (<) 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 1, 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.d[1]...d[N]*10^k (d[1]>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

题意

  比较两个数的科学计数法是否相同,相同输出YES,否则输出NO。本题不需要考虑四舍五入。

思路

  把接收到的两个数删除掉前导的0。然后分为两种情况:一种是.00XXXX形式;另一种是XXXX.XXXX形式。

  如果是.00XXXX形式,删除小数点和小数点后面的0,直到碰到不为0的数,每删一个0,指数减1。

  如果是XXXX.XXXX形式,遍历字符串直到碰到小数点,把小数点删除。每遍历一个数,指数加1。

  最后比较改变后的字符串和指数,输出结果。注意输入  000.0  时输出 YES 0.000*^

code:

 #include<bits/stdc++.h>
using namespace std;
string num1, num2;
int n;
static string turn(string a, int &e){//e前面加&,值才会被修改
string result="0.";
while(a.size()>&&a[]==''){//删除前导0
a.erase(a.begin());
}
if(a[]=='.'){//0.XXXXXX形式
a.erase(a.begin());
while(a.size()> && a[]==''){
a.erase(a.begin());
e--;
}
}else{//XXXX.XXXX形式
int k = ;
while(k < a.size() && a[k]!='.'){
e++;
k++;
}
if(k<a.size()) a.erase(a.begin()+k);
}
if(a.size()==) e = ;//删除0和小数点后长度为0
int num = , k = ;
while(num < n){
if(k < a.size()) result += a[k++];
else result += '';
num++;
}
return result;
}
int main(){
int e1 = , e2 = ;
cin>>n>>num1>>num2;
string s1 = turn(num1,e1);
string s2 = turn(num2,e2);
if(s1 == s2 && e1 == e2)
cout<<"YES "<<s1<<"*10^"<<e1;
else
cout<<"NO "<<s1<<"*10^"<<e1<<" "<<s2<<"*10^"<<e2;
return ;
}