1060 Are They Equal
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 • 1
Sample Output 1:
YES 0.123*10^5
Sample Input 2:
3 120 128 • 1
Sample Output 2:
NO 0.120*10^3 0.128*10^3
思路
这道题主要难点就在于将给定的浮点数转换成 0. x ∗ 1 0 y 0.x*10^y0.x∗10
y
的形式,我们这里来讲如何处理字符串:
先找到 . ,如果是整数需要人为在后面加上一个 . ,因为我们要得到 . 的位置 k kk ,用于分隔两边的数字。
将 . 两边的数字即字符串合并,然后去除多余的前缀 0 00 。
判断去除完 0 00 后字符串是否为空,要将 k kk 也置 0 00 ,防止其越界。
判断有效位数 n nn 与字符串的长度的大小,如果字符串位数大于有效位数则要进行截断,反之补 0 00 。
返回时,注意字符串的格式。
代码
#include<bits/stdc++.h> using namespace std; int n; string a, b; string change(string str, int n) { //找到'.',如果没有则加在后面并且找到其所在位置 int k = str.find("."); if (k == -1) str += ".", k = str.find("."); //合并'.'两边的字符串,并去除前缀0 string s = str.substr(0, k) + str.substr(k + 1); while (s.size() && s[0] == '0') s = s.substr(1), k--; if (s.empty()) k = 0; //字符串为空k也要置0 if (s.size() > n) s = s.substr(0, n); //字符串长度大于有效位要截断 else s += string(n - s.size(), '0'); //反之要补0 return "0." + s + "*10^" + to_string(k); } int main() { cin >> n >> a >> b; a = change(a, n); b = change(b, n); if (a == b) cout << "YES " << a << endl; else cout << "NO " << a << " " << b << endl; return 0; }