题目:
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.d1...dN*10^k" (d1>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.9Sample Output 1:
YES 0.123*10^5Sample Input 2:
3 120 128Sample Output 2:
NO 0.120*10^3 0.128*10^3思路:
1.先根据输入的字符串找到其10的幂数,并删除小数点及无效的0,这里注意需要考虑到指针越界的问题;
2.比较时先比较幂次,相等再比较其有效位数;
3.注意有效位数N与字符串的有效字符,如果有效字符不够,则在后面用0补足。
代码:
#include<iostream>
#include<cstring>
#include<string>
#include<math.h>
using namespace std;
int find_k(string &s)
{
int i, j, k;
//找到小数点位置
i = 0;
while (i < s.size())
{
if (s[i] == '.')
break;
++i;
}
for (j = 0; j < i;++j )
{
//在整数部分,找到第一个不为0的数字
if (s[j] != '0')
break;
}
if (j < i)
{
//在整数部分找到不为0的数字
k = i - j; //位数
//删除小数点
if (i < s.size())
{
s.erase(s.begin() + i);
}
//删除前面的无效0
if (j > 0)
{
s.erase(s.begin(), s.begin() + j);
}
return k;
}
else
{
//小数情况,这里如果小数点,则j=i,如果没有j=s.size()
if (j < s.size())
{
for (j = i + 1; j < s.size(); ++j)
{
if (s[j] != '0')
break;
}
}
//现在的j指向有效数字di1位
if (j < s.size())
{
k = i-j+1;
if (j - i >= 1)
{
s.erase(s.begin(), s.begin() + j);
}
return k;
}
else
{
//数为0;
s.clear();
s = "0";
return 0;
}
}
}
int main()
{
int N;
cin >> N;
string A, B;
cin >> A >> B;
int k1, k2,i;
//查找有效位数
k1 = find_k(A);
k2 = find_k(B);
string aa, bb;
aa.resize(N);
bb.resize(N);
for (i = 0; i < N && i<A.size() ; ++i)
{
aa[i] = A[i];
}
while (i < N)
{
aa[i] = '0';
++i;
}
for (i = 0; i < B.size() && i<N; ++i)
{
bb[i] = B[i];
}
while (i <N)
{
bb[i] = '0';
++i;
}
bool flag = 0;
if (k1 != k2)
flag = 1;
if (!flag)
{
for (i = 0; i < N; ++i)
{
if (aa[i] != bb[i])
{
flag = 1;
break;
}
}
}
if (flag)
{
printf("NO 0.%s*10^%d 0.%s*10^%d\n",aa.c_str(),k1,bb.c_str(),k2);
}
else
{
printf("YES 0.%s*10^%d\n", aa.c_str(), k1);
}
system("pause");
return 0;
}