PTA(Advanced Level)1060.Are They Equal

Posted martinlwx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PTA(Advanced Level)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

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

思路

  • 题意就是将给你的数转换为科学计数法的形式((0.d_1d_2d_3... imes10^k)),比较小数点后前n位是否一致即可
  • 容易想到我们可以按照是否(>1)来分类处理不同的字符串
    • (>1):主要看有没有小数点,找到小数点来确定位数
    • (<1):主要是去除小数点到有效数字前的0
  • ?数据是会有前导0的情况出现的,要小心

代码

#include<bits/stdc++.h>
using namespace std;
int n;
string transfer(string s, int &x)
{
	while(s.size() > 0 && s[0] == ‘0‘)	s.erase(s.begin());		//为了应对形如000.0这样的数据,去掉小数点前面的0
	if(s[0] != ‘.‘)		// >1的数
	{
		std::size_t pos = s.find(".");	// 查看是否有小数点
		if(pos != s.npos)	// 如果找到了小数点
		{
			x = pos;
			s.erase(s.begin() + pos);	// 去除小数点
		}else	x = s.size();
	}else		// <1的数
	{
		s.erase(s.begin());
		while(s.size() > 0 && s[0] == ‘0‘)		// 处理形同0.000234这样的数据,
		{
			s.erase(s.begin());
			x--;
		}
	}

	if(s.size() == 0)	x = 0;

	string ans;
	if(s.size() > n)
		for(int i=0;i<n;i++)	ans += s[i];
	else
	{
		for(int i=0;i<s.size();i++)		ans += s[i];
		for(int i=0;i<n - s.size();i++)		ans += ‘0‘;		// 不足的添加0补足位数
	}
	return ans;
}	// 原始字符串->有效数字^指数
int main()
{
	string a, b, c, d;
	cin >> n >> a >> b;
	int x1 = 0, x2 = 0;
	c = transfer(a, x1);
	d = transfer(b, x2);
	if(c == d && x1 == x2)
		cout << "YES 0." << c << "*10^" << x1;
	else
		cout << "NO 0." << c << "*10^" << x1 << " 0." << d << "*10^" << x2;
	return 0;
}

引用

https://pintia.cn/problem-sets/994805342720868352/problems/994805413520719872

以上是关于PTA(Advanced Level)1060.Are They Equal的主要内容,如果未能解决你的问题,请参考以下文章

PTA(Advanced Level)1025.PAT Ranking

PTA (Advanced Level)1022 Digital Library

PTA(Advanced Level)1059.Prime Factors

PTA(Advanced Level)1044.Shopping in Mars

PTA(Advanced Level)1036.Boys vs Girls

PTA (Advanced Level)1013 Battle Over Cities