1060 Are They Equal-PAT甲级

本文探讨了在特定机器精度下,如何判断两个浮点数是否被视为相等的问题。通过实例解析,介绍了如何将浮点数转换为科学计数法表示,并比较其有效数字和指数部分,以确定两数在给定精度下的等价性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

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.

 

输入描述:

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.


 

输出描述:

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.

 

输入例子:

3 12300 12358.9

 

输出例子:

YES 0.123*10^5

字符串的处理

当涉及到科学技术法表示时,用一个字符串存储有效数字,一个整数存储指数,此处还需注意在判题的过程中,0的指数应该为0

满分代码如下:

#include<bits/stdc++.h>
using namespace std;
int n;
string a,b;
int exe(string &s,string&at,int k){
	//将字符串思维有效位数存储在at中,并返回指数
	int point=s.size(),index=-1;//小数点和第一个非零数的位置
	for(int i=0;i<s.size();i++){
		//遍历字符串
		if(s[i]=='.') point=i;
		else if(index!=-1&&at.size()<k) at+=s[i];
		else if(index==-1&&s[i]!='0'){
			index=i;
			at+=s[i];
		} 
	} 
	while(at.size()<k) at+='0';
	if(index==-1) return 0;
	point-=index;//小数点位置减去第一位非零数位置得到指数
	return point<0?point+1:point;
	//负数的话加1 	
}
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	cin>>n>>a>>b;
	string atemp="",btemp="";
	int ae=exe(a,atemp,n),be=exe(b,btemp,n);
	if(ae==be&&atemp==btemp){
		cout<<"YES 0."<<atemp<<"*10^"<<ae;
	}else{
		cout<<"NO 0."<<atemp<<"*10^"<<ae<<" 0."<<btemp<<"*10^"<<be;
	}
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值