PAT A1060 Are They Equal(科学计数法)

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×10​5​​ 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 10​100​​, 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,去掉小数点,记录指数,补位,等...


第一步:除去前导0,比如:002.1 , 00345 ,
1)再判断是否去掉后length=0,如果是则判断为0。如000.00

第二步:<1情况,
1)去掉小数点
2)去掉小数点后的0并记录指数 。比如:0.01 ->.01->1,10^-1。

第三步:>=1情况
1)找到小数点位置,并去掉

第四步:去位与补位
注:补位填0

代码:
 

#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;

int n;//有效位数 

string deal(string& a,int& e){
	//去掉前导0 
	while(a[0]=='0'&&a.length()>0){
		a.erase(a.begin());
	}
	//去掉前导0,长度为0,则判断出是0。比如:00.00情况,为0 
	if(a.length()==0){
		e=0;
	}
	//当小于1时 
	if(a[0]=='.'){
		a.erase(a.begin());//去掉小数点
		//去掉小数点后的0 
		while(a[0]=='0'&&a.length()>0){
			a.erase(a.begin());
			e--; 
		}
	}
	//当>=1时候 
	else{
		int k=0;//下标找到小数点的位置 
		while(a[k]!='.'&&k<a.length()){
			e++;
			k++;
		}
		if(a[k]=='.'){
			a.erase(a.begin()+k);
		}
	}

	
	
	//删除多余位
	if(n<a.length()){
		a.erase(n,a.length()-n);
	}else{//补充0位 
		while(a.length()!=n){
			a=a+'0';
		}
	} 
	return a;
}

int main(){
	string a,b;	
	cin>>n>>a>>b;
	int e1=0;
	int e2=0;
	if(deal(a,e1)==deal(b,e2)&&e1==e2){
		cout<<"YES 0."<<a<<"*10^"<<e1<<endl;
	}else{
		cout<<"NO 0."<<a<<"*10^"<<e1<<" 0."<<b<<"*10^"<<e2<<endl;
	}
} 

猜你喜欢

转载自blog.csdn.net/qq_41877184/article/details/89765896
今日推荐