模擬_1060 Are They Equal (25 分)
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.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 Aand 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.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
這個題有好多細節需要考慮 ,首先是前導零,例如000.5的情況
然後如果去除前導零之後,第一位為‘.’,這是要判斷後面是否接著是0,例如000.0005 這時,需要繼續向後刪除,因為只有為0的情況下,d[1]才能為0
最後取出完前導零,判斷字串是否還有剩餘,沒有的話,就證明這個字串為0,否則不為0
接著計算有效數字,計算偏移量即可
#include <vector>
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 105;
char * change(int N,string a)
{
char *num = (char *)malloc(N*sizeof(char));
int index = 0,len = a.length(),j = 0;
for(int i = 0;i < N;i ++)
{
if(a[j] == '.')
{
j++;i--;continue;
}
if(j < len)
num[index++] = a[j++];
else
{
while(i++ < N)
num[index++] = '0';
break;
}
}
return num;
}
void format(string &a,int &index)
{
while(a[0] == '0') a.erase(0,1); //前導零
while(a[0] == '.') a.erase(0,1); //如果小數點後面也是零
while(a[0] == '0') a.erase(0,1),index --; //也要去除000.005
}
int main()
{
int N;
string a,b;
cin>>N>>a>>b;
int indexa=0,indexb = 0;
format(a,indexa);
format(b,indexb);
int lena = a.length(),lenb = b.length();
if(lena == 0) indexa = 0;
if(lenb == 0) indexb = 0;
if(indexa == 0)
for(int i =0 ;i < lena;i ++) if(a[i] != '.') indexa ++ ;else break;
if(indexb == 0)
for(int i = 0;i < lenb;i ++) if(b[i] != '.') indexb ++ ;else break;
char *aa = change(N,a);
char *bb = change(N,b);
if(strcmp(aa,bb) == 0 && indexa == indexb)
{
printf("YES ");
cout << "0."<<aa<<"*10^"<<indexa<<endl;
}
else
{
printf("NO ");
cout << "0."<<aa<<"*10^"<<indexa<< " 0."<<bb<<"*10^"<<indexb<<endl;
}
}