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.12310^5
Sample Input 2:
3 120 128
Sample Output 2:
NO 0.12010^3 0.12810^3
题意:
给出两个数,将他们写成保留N位小数的科学记数法后是否相等,如果相等则输出YES,并输出转换结果,如果不等,输出NO,并给出两个数的转换结果
思路:
1.根据题目要求只需判断科学记数法的本体部分和指数部分是否对应相等
2.数据有可能出现0.001这种实数前面还有若干0的情况,第一步先去除所有前导0,然后再判断是大于1的数还是小于1的数(通过去除0后判断第一位是否为小数点确定)
3.如果是0.*****这种形式,本体部分是从小数点后第一个不为0的数开始的 3位,指数则是小数点与该非零位之间的0的个数的相反数
4.如果是 ****.***这种形式,假设第一位不为0,本体部分就是从第一位开始后3位,指数部分是小数点前面的总位数。
C++代码:
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int n;
string deal(string s,int& e){
int k=0;
while(s.length()>0&&s[0]=='0'){
s.erase(s.begin());//去掉前导0
}
if(s[0]=='.'){//s是小于1的小数
s.erase(s.begin());
while(s.length()>0&&s[0]=='0'){
s.erase(s.begin());//去掉小数点后非零位所有零
e--;
}
}
else{
while(k<s.length()&&s[k]!='.'){
k++;
e++;
}
if(k<s.length()){
s.erase(s.begin()+k);
}
}
if(s.length()==0){
e=0;
}
int num=0;
k=0;
string res;
while(num<n){
if(k<s.length()){
res=res+s[k++];
}
else res=res+'0';
num++;
}
return res;
}
int main(){
string str1,str2,str3,str4;
cin>>n>>str1>>str2;
int e1=0,e2=0;//e1、e2为s1和s2的指数
str3=deal(str1,e1);
str4=deal(str2,e2);
if(str3==str4&&e1==e2){
cout<<"YES 0."<<str3<<"*10^"<<e1<<endl;
}
else{
cout<<"NO 0."<<str3<<"*10^"<<e1<<" 0."<<str4<<"*10^"<<e2<<endl;
}
return 0;
}