题目描述
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×10^5 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 10^100, 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.12010^3 0.12810^3
求解思路
考察string有关的处理函数的使用
利用字符串处理函数获得去掉前导0和小数点,以及小数点后第一位非零数前的零得到的字符串,如果处理后的字符串长度大于n则截断,否则补0。将其表示成科学计数法即可
实现代码
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
int n;
string deal(string s,int &eps)
{
/*对字符串首先进行预处理*/
int index=0; //字符串索引
/*去掉s的前导0*/
while(s.length()>0&&s[0]=='0')
{
s.erase(s.begin());
}
/*
如果去掉前导0后是小数点,则说明s是小于1的小鼠
去掉小数点,并且去掉一位小数点后非零位前的所有零
每去掉一个零,指数e减1
*/
if(s[0]=='.')
{
s.erase(s.begin());
while(s.length()>0&&s[0]=='0')
{
s.erase(s.begin());
eps--;
}
}
/*
如果去掉前导0后不是小数点,则找到后面的饿小数点进行删除
在寻找小数点的循环中,只要没有遇到小数点,就让指数eps++
如果while结束后index<s.length(),说明遇到了小数点,把小数点删除即可
*/
else
{
while(index<s.length()&&s[index]!='.')
{
index++;
eps++;
}
if(index<s.length())
s.erase(s.begin()+index);
}
/*如果去除前导0后s的长度变为0,则说明这个数是0*/
if(s.length()==0) eps=0;
/*处理字符串*/
int i=0;
index=0;
string out;
/*只要精度还没有到n,只要还有数字就添加到out末尾,否则out末尾添加0*/
while(i<n)
{
if(index<s.length())
out+=s[index++];
else out+='0';
i++;
}
return out;
}
void solve()
{
string s1,s2,s3,s4;
cin>>n>>s1>>s2;
int e1=0,e2=0;
s3=deal(s1,e1);
s4=deal(s2,e2);
if(s3==s4&&e1==e2)
cout<<"YES 0."<<s3<<"*10^"<<e1<<endl;
else cout<<"NO 0."<<s3<<"*10^"<<e1<<" 0."<<s4<<"*10^"<<e2<<endl;
}
int main()
{
solve();
return 0;
}