PAT 1060. Are They Equal (25)

xiaoxiao2021-02-28  101

1060. Are They Equal (25)

时间限制 100 ms 内存限制 65536 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

很纠结的一道题。描述很简单,处理起来挺麻烦的。思路就是确定出原始数组第一个有效数字的位置和小数点的位置,从而确定科学计数法的指数。但是输出这个指数时很麻烦,不好转换成数组。机智的我想了个办法,把指数放在数组用不到的位置(x[148]),就很方便输出了。这题还有个坑点是俩数字都是0时,要输出 {0.n个0*10^0},题目说的不清楚,要自己试,很坑。

#include<string> #include<stdio.h> #include<iostream> #include<string.h> #include<queue> #include<algorithm> #include<map> #include<set> #include<math.h> #include<stack> #include<vector> using namespace std; char a[150],b[150]; int n; char aa[160],bb[160]; void geet(char x[],char y[]) { int p1=0; int p2=2; int p3=0; //确定小数点位置 int p4=0; //确定第一个有效数字位置 for(;p3<strlen(x);p3++) if(x[p3]=='.') break; for(;p4<strlen(x);p4++) if(x[p4]!='0'&&x[p4]!='.') break; for(int i=strlen(x);i<140;i++) //害怕原数组长度不够,扩长度。 x[i]='0'; x[140]=0; p1=p4; int bit; if(p3<p4) bit=p3-p4+1; //计算科学计数法的指数 else bit=p3-p4; y[0]='0'; y[1]='.'; while(1) { if(x[p1]=='.') p1++; y[p2++]=x[p1++]; if(p2==n+2) break; } y[p2++]='*'; y[p2++]='1'; y[p2++]='0'; y[p2++]='^'; y[p2++]=0; y[148]=bit; } int main() { cin>>n>>a>>b; geet(a,aa); geet(b,bb); int fllag=0; //判断两边是不是都是0 for(int i=0;aa[i]!='*';i++) if(aa[i]!='0'&&aa[i]!='.') { fllag=1;break; } for(int i=0;bb[i]!='*';i++) if(bb[i]!='0'&&bb[i]!='.') { fllag=1;break; } if(fllag==0) { cout<<"YES 0."; for(int i=0;i<n;i++) cout<<0; cout<<"*10^0"; } else { //开始正式判断 int flag=0; if(strcmp(aa,bb)==0&&aa[148]==bb[148]) cout<<"YES "; else { flag=1;cout<<"NO ";} int x=aa[148]; int y=bb[148]; cout<<aa<<x; if(flag==1) cout<<' '<<bb<<y; } return 0; }

转载请注明原文地址: https://www.6miu.com/read-71822.html

最新回复(0)