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×105with 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.
解答:
天将降大任于斯人也,必先苦其心志,劳其筋骨。。
不说了,今天上午都花在了这道题上,我的代码始终23分,有一个用例不过,下午借鉴他人的实现思路,终于AC!
思路:
(1)用两个值firstPos和pointPos保存一个浮点数的第一个非零值位置和小数点位置,这样可以完美的解决0023.34、0.0014等用例测试;
(2)用一个字符串保存基数,第一个位置就是firstPos所指的位置;
(3)对(1)中的情况进行补充,如果出现整数,即123,那么pointPos就被初始化为s.size(),即默认在最后面添加了小数点;如果出现数0,那么对firstPos和pointPos同时初始化为s.size();
(4)输出时,判定基数是否相同,同时指数是否相同。
AC代码如下:
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
typedef struct{
string s; //存储0.xxxxxx的xxxxxx部分
int bit; //存储指数
}num;
int n;
string a, b;
num handle(const string& a)
{
num tmp;
int firstPos = -1, pointPos = -1;
for(int i = 0; i < a.size(); ++i)
{
if(a[i] == '.')
{
pointPos = i;
}
else if(isdigit(a[i]) && a[i] != '0' && firstPos == -1)
{
firstPos = i;
tmp.s.push_back(a[i]);
}
else if(firstPos != -1 && isdigit(a[i]))
{
tmp.s.push_back(a[i]);
}
}
//如果没有小数点,那么默认在整数最后面有小数点
if(pointPos == -1) pointPos = a.size();
//firstPos是-1,那么数字一定是0
if(firstPos == -1)
{
firstPos = pointPos = a.size();
}
//对数进行补0
if(tmp.s.size() < n)
{
tmp.s.append(n - tmp.s.size(), '0');
}
else
{
tmp.s = tmp.s.erase(n);
}
//cout << pointPos << " " << firstPos << endl;
if(pointPos < firstPos) tmp.bit = pointPos - firstPos + 1;
else tmp.bit = pointPos - firstPos;
return tmp;
}
int main()
{
cin >> n >> a >> b;
num result1, result2;
result1 = handle(a);
result2 = handle(b);
if(result1.s == result2.s && result1.bit == result2.bit)
{
cout << "YES 0." << result1.s << "*10^" << result1.bit << endl;
}
else
{
cout << "NO";
cout << " 0." << result1.s << "*10^" << result1.bit;
cout << " 0." << result2.s << "*10^" << result2.bit << endl;
}
return 0;
}