PAT A 1060. Are They Equal (25)

题目

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.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

 

求两个数在n位有效位时是否相等。

注意:

1、转换后小数点后第1位应当为非0数,这个数字可出现在原数的小数点之后,如0.00123;

2、原有数据可能长度不足,如0.00123取5位有效数字,后面的2位应认为是0;

3、注意计算指数时,系数为正和系数为负计算式有区别

 

代码:

#include <iostream>
#include <string>
using namespace std;

int Transform(string &s,int n);	//转换格式,s为输入数字的字符串结构,转换后取有效数字部分,0的话补足够位数的0;返回指数
void Put_out(string s,int exp,int n);	//输出数据

int main()
{
	int n;
	string s1,s2;
	cin>>n>>s1>>s2;		//输入

	int exp1,exp2;	//转换
	exp1=Transform(s1,n);
	exp2=Transform(s2,n);
	if(exp1!=exp2)	//指数不等,直接跳出
	{
		cout<<"NO ";
		Put_out(s1,exp1,n);
		cout<<" ";
		Put_out(s2,exp2,n);
		return 0;
	}
	else	//指数相等
	{
		for(int i=0;i<n;i++)	//判断有效位范围内是否相等
		{
			if(s1[i]!=s2[i])	//存在不相等的有效位
			{
				cout<<"NO ";
				Put_out(s1,exp1,n);
				cout<<" ";
				Put_out(s2,exp2,n);
				return 0;
			}
		}	//有效位都相等
		cout<<"YES ";
		Put_out(s1,exp1,n);
		return 0;
	}
	return 0;
}

void Put_out(string s,int exp,int n)	//格式化输出
{
	int i;
	cout<<"0.";
	for(i=0;i<n;i++)
		cout<<s[i];
	cout<<"*10^"<<exp;
}

int Transform(string &s,int n)	//转换格式
{
	int i,j;
	int pos_point=s.size();	//小数点位置
	int pos_begin=s.size();	//第一个非'0',非'.'的有效字符的位置,
	for(i=0;i<s.size();i++)
		if(s[i]=='.')
		{
			pos_point=i;
			break;
		}
	for(i=0;i<s.size();i++)
		if(s[i]!='0'&&s[i]!='.')
		{
			pos_begin=i;
			break;
		}
	if(pos_begin==s.size())	//没有有效位,即数字为0
	{
		s="0";
		for(i=0;i<n;i++)
			s+="0";
		return 0;
	}
	for(j=0,i=pos_begin;j<n+2;i++)	//转化有效数据
	{
		if(i<s.size())	//数据在原有效数据段内
		{
			if(s[i]!='.')
				s[j++]=s[i];
		}
		else if(j<s.size())	//超出范围,但位数不到原数据长度
			s[j++]='0';
		else	//超出原数据长度,n大于输入数据的位数
		{
			s+="0";
			j++;
		}
	}
	if(pos_point-pos_begin>=0)	//指数大于0
		return pos_point-pos_begin;
	else	//指数小于0,!!!注意小于零时指数计算是不同的
		return pos_point-pos_begin+1;
}


 

 

 

 

 

你可能感兴趣的:(C++,pat)