PTA-string(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 5with 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* 103 0.128*103

思路

分两种情况讨论:
1.xxx.yyy
2.0.xxx
首先需要知道两数的指数以及有效位数截断后的数,如果这两个都相等则两数相等。
首先去除前导0,接着判断下一位是否为小数点,如果是则说明这个数小于0,应再去除小数点后到有效位数之前的0,而指数绝对值就为这段0的个数;

如果否则说明这个数大于0,应遍历直到找到小数点,指数为从头到小数点之间的数的个数,并去掉小数点(没有可以省略)。

经过这一步已经求出来指数大小了,我们需要对剩余的字符串做截断处理:
如果小于有效位数,则在字符串首添加0;如果大于有效位数,则截取前有效位即可。
最后按照格式输出结果。

#include<bits/stdc++.h>
using namespace std;
int n;
string tackle(string str,int &e){
	while(str.size()>0&&str[0]=='0'){
		str.erase(str.begin());
	} 
	if(str[0]=='.'){
		str.erase(str.begin());
		while(str.size()>0&&str[0]=='0'){
			str.erase(str.begin());
			e--;
		}	
	}
	else{
		for(int i=0;i<str.size();i++){
			if(str[i]=='.'){
				str.erase(str.begin()+i);
				break;
			}
			else{
				e++;
			}
		}
	}
	if(str.size()==0) e=0;
	while(str.size()<n){
		str.insert(str.begin(),'0');
	}
	if(str.size()>n){
		str.erase(str.begin()+n,str.end());
	}
	return str;
}
int main(){
	cin>>n;
	string s1,s2,x,y;
	cin>>s1>>s2;
	int e1=0,e2=0;
	x=tackle(s1,e1);
	y=tackle(s2,e2);
	//cout<<x<<' '<<y<<endl;
	if(x==y&&e1==e2){
		printf("YES 0.%s*10^%d",x.c_str(),e1);
	}else{
		printf("NO 0.%s*10^%d 0.%s*10^%d",x.c_str(),e1,y.c_str(),e2);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

新西兰做的饭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值