PAT 甲级 A1060

1060 Are They Equal (25分)

题目描述

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 10​^{100} ​​ , and that its total digit number is less than 100.

输入格式

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.

输出格式

For each test case, print your results in N lines. Each line corresponds to one student, in the following format: first print the student’s name, then the total number of registered courses of that student, and finally the indices of the courses in increasing order. The query results must be printed in the same order as input. All the data in a line must be separated by a space, with no extra space at the end of the line.

Sample Input1:

3 12300 12358.9

Sample Output1:

YES 0.123*10^5

Sample Input2:

3 120 128

Sample Output2:

NO 0.120*10^3 0.128*10^3

总结

  1. 首先搭个大框架,分两种情况方便讨论:一种是有小数点一种是没有小数点。
  2. 但这题有个巨坑!就是可能存在000123.56这种情况,所以在处理前,一定要去除真正有效部分前面的0。还有需要注意的是,如果有效部分本身就是0,就需要进行特殊处理,如0000.000。
  3. 此外用引用的方式保存移位结果,大致思路就是这样了~~

AC代码

#include <iostream>
#include<string>
using namespace std;
string toStdFormat(string a, int n, int&k) {
	k = 0;
	while (a[0] == '0'&&a.size() > 0)	a.erase(a.begin());   //去掉前导0
	if (a[0] == '.') {
		a.erase(a.begin());
		while (a[0] == '0'&&a.size() > 0) {
			a.erase(a.begin());   //去掉前导0
			k--;
		}
		if (a.size() == 0) k = 0;	//全为0
	}
	else { //必定是数字且首位不为.也不为0, 分两种情况,如  (1)1235 (2) 1235.645
		for (int i = 0; i < a.size(); i++) {
			if (a[i] != '.') {
				k++;
			}
			else {
				a.erase(a.begin() + i);
				break;
			}
		}
	}
	//把a搞到n位,不够补0,多则chop
	while (a.size() < n) a += '0';
	if (a.size() > n) {
		a = a.substr(0, n);
	}
	return "0." + a ;
}
int main() {
	int n;
	string a, b;
	while (cin >> n >> a >> b) {
		int k1, k2;
		a = toStdFormat(a, n, k1);
		b = toStdFormat(b, n, k2);
		if (a == b && k1 == k2) {
			cout << "YES " << a << "*10^" << k1 << endl;
		}
		else {
			cout << "NO " << a << "*10^" << k1 << " " << b << "*10^" << k2 << endl;
		}
	}
	return 0;
}
发布了16 篇原创文章 · 获赞 0 · 访问量 364

猜你喜欢

转载自blog.csdn.net/qq_38507937/article/details/104273708