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.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
-----------------------------------这是题目和解题的分割线-----------------------------------
这道题坑太多了,我偷懒参考的代码。
思路如下:
输入的数据有两种情况,①0.xxxxxx ②xxxxx.xxxx,这两类要分开讨论。
如何区分:这里还得提一提题目的大大大陷阱,输入不是一般意义上的,会出现000010.23/0.0000等大量多余零的情况。如果字符串的第一个字母为零,循环删除,直到非零或者字符串末端。循环中断时,字符串的第一个字符若为小数点,则是情况①,否则是情况②。
情况①解决方法:输出不仅要考虑本体还要考虑指数。本体是小数点后第一个非零数字开始的N位数,指数则是该小数点与非零数字之间0个数的相反数(0.xxxxx指数为负)。
情况②解决方法:本体是区分后,第一位数到第N位数。指数为遇到小数点前的数字的个数。
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int n;
//&e:引用调用和传值传址不同,是C++特有的,且不拷贝值或者地址,实参改变是因为用的是同一块内存
string solveFx(string s,int& e)
{
//删除多余的零
while(s[0]=='0'&&s.length()>0)
s.erase(s.begin());
//情况① 0.xxxxxx
if(s[0]=='.')
{
s.erase(s.begin()); //删除小数点
//删除小数点后非零位前所有的零(本体不需要这部分)
while(s[0]=='0'&&s.length()>0)
{
s.erase(s.begin());
e--;//记录指数
}
}
//情况②:xxxx.xxxx
else
{
int k = 0;
//寻找小数点
while(s[k]!='.'&&k<s.length())
{
k++;
e++; //记录指数
}
//找到小数点
if(k<s.length())
s.erase(s.begin()+k); //删除小数点
}
//如果经过以上操作位数为0,说明是0(只是伪装成了0.00/0000)
if(s.length()==0) e = 0; //指数为0
int cnt = 0,x = 0;
string newS;
//精度还没到n
while(cnt<n)
{
//只要还有数字,就加到新字符串的末尾
if(x<s.length()) newS += s[x++];
else newS += '0'; //没有就自动补零
cnt++;
}
return newS;
}
int main()
{
string s1,s2;
cin>>n>>s1>>s2;
int e1 = 0,e2 = 0;
string s3 = solveFx(s1,e1);
string s4 = solveFx(s2,e2);
//如果本体和指数均相等
if(s3==s4&&e1==e2)
cout<<"YES"<<" 0."<<s3<<"*10^"<<e1;
else
cout<<"NO"<<" 0."<<s3<<"*10^"<<e1<<" 0."<<s4<<"*10^"<<e2;
return 0;
}