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.120*10^3 0.128*10^3
题意: 给2个长长度小于100的大浮点数,要求保留n个有效数字,再判断保留完是否相等,并以 0.xxx*10^k 的形式输出。
思路是直接求出最终的表示形式,以string来处理和存储,再判断是否相等。
首先明确有效数字的定义:从数最左边开始,第一个不是0的数字开始算作有效数字(在此之后的0也算) 。
观察科学计数的形式,发现只有有效数字部分不同,其他是固定的,所以用一个string来存储有效数字。
求有效数字: 用string的 find_first_not_of(“0”) 找到第一个有效数字的位置pos。对于0.001这样中间有小数点的情况,只要一开始用 find() 函数求出并记住小数点位置,然后用 erase() 删掉小数点即可。
从pos开始的n个数都是有效数字,可以用string的构造函数把这个区间的字符拷贝过来,不足n位的话用循环在后面补0。
求指数: 因为这个转换是把小数点移到第一个有效数字前,所以
指数 = 小数点实际位置 - 第一个有效数字位置
坑点:
1、有前导0的情况,比如输入的数是0002.12
2、数等于0的情况(0或000.00或0.000),规定是指数必须为0
(对应第4和第6个数据)
代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n, success = 0;
string a, b;
int main(){
cin >> n >> a >> b;
int pa, pb, pos1, pos2; // pa,pb表示两个数的小数点实际位置,pos1、2表示第一个有效数字的位置
if(a.find(".") == a.npos)
a += ".0";
if(b.find(".") == b.npos) // 补上小数点以便同一计算
b += ".0";
pa = a.find("."), pb = b.find(".");
string aa = a, bb = b; // aa和bb最终将存放每个数的所有有效数字(仅数字)
aa.erase(aa.find("."), 1);
bb.erase(bb.find("."), 1); // 去掉小数点
pos1 = aa.find_first_not_of("0"), pos2 = bb.find_first_not_of("0");
aa = pos1 == (int)aa.npos? "0" : string(aa, pos1, n);
bb = pos2 == (int)bb.npos? "0" : string(bb, pos2, n);// 注意判断数是0的情况!
while(aa.length() < n)
aa += '0';
while(bb.length() < n) // 位数不足有效数字个数则用0补
bb += '0';
int k1 = pa - pos1, k2 = pb - pos2; // 指数
if(aa == string(n, '0'))
k1 = 0;
if(bb == string(n, '0')) // 数是0的情况,10的指数规定为0
k2 = 0;
string resa = "0." + string(aa, 0, n) + "*10^" + to_string(k1);
string resb = "0." + string(bb, 0, n) + "*10^" + to_string(k2);
if(resa == resb)
success = true;
if(success)
cout << "YES " << resa << endl;
else
cout << "NO " << resa << ' ' << resb << endl;
return 0;
}