现在的位置: 首页 > 综合 > 正文

【PAT1060】Are They Equal

2017年05月08日 ⁄ 综合 ⁄ 共 2119字 ⁄ 字号 评论关闭

1060. Are They Equal (25)

时间限制
50 ms
内存限制
32000 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

题意:将两个float型数据使用科学计数法表示,并比较两者是否相同

关键:要考虑所给输入数据的多种情况,比如 0 , 0.0,0.0123,05.032,00.020等这种比较特殊的情况。

代码如下:

#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

ifstream fin("in.txt");
#define cin fin

int convert(const char* c,int n,char* &res)
{
	int point,count;
	point = count = 0;
	int i=0,j=0;
	while(c[i]=='0')i++;		//先略去最前面的'0'

	if(c[i]=='.')		//形式为 (0)*.##
	{		
		bool isBegin = false;
		while(c[i]!='\0')
		{
			if(c[i]=='.')
			{
				point = 1;
			}else if(c[i]!='0')
			{
				isBegin = true;
			}
			
			if(isBegin){
				if(count<n)
				{
					res[count]=c[i];
					count++;
				}
			}else
			{
				point--;
			}
			i++;
		}
		if(!isBegin)point=0;
	}else								//形式为 (0)*#.##
	{
		j=i;
		while(c[i]!='\0')
		{
			if(c[i]=='.')
			{
				point = i-j;
			}else
			{
				if(count<n)
				{
					res[count]=c[i];
					count++;
				}
			}
			i++;
		}
		if(point==0)//如果没有. 则等于数字个数(去掉前面的0)	
			point = i-j;	
	}
	
	if(count<n)			//如果数字个数不足,补'0'
	{
		i = count;
		while(i<n)
		{
			res[i]='0';
			i++;
		}
	}
	res[n]='\0';
	return point;
}

int main()
{
   int n;
   cin>>n;
   char A[105],B[105];
   cin>>A>>B;
   int Ac,Bc;
   char *Ares,*Bres;
   Ares = new char[n+1];
   Bres = new char[n+1];
   Ac = convert(A,n,Ares);
   Bc = convert(B,n,Bres);
   if(Ac==Bc && strcmp(Ares,Bres)==0)
   {
		cout<<"YES 0."<<Ares<<"*10^"<<Ac<<endl;
   }else
   {
		cout<<"NO 0."<<Ares<<"*10^"<<Ac<<" 0."<<Bres<<"*10^"<<Bc<<endl;
   }
   system("PAUSE");
   return 0;
}

抱歉!评论已关闭.