欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

【PAT】A1060 Are They Equal *

发布时间:2025/3/20 56 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【PAT】A1060 Are They Equal * 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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

 解题思路:

见代码注释,摘自《算法笔记》

代码:

#include <stdio.h> #include <string> #include <iostream> using namespace std;int n; //有效位数 string deal(string s,int& e){ //e被改写了,就是在内存中的地址上的数字在本函数中不断被改写,所以在主函数中读取的时候是本函数修改过的值,这也是int& e,修改内存中e的数值的用意所在 int k=0; //s的下标while(s.length()>0&&s[0]=='0'){ //前导数是0要去掉,如0000234.23这种情况,不加以判断可能会在e指数的数值上出错 s.erase(s.begin()); } if(s[0]=='.'){ //去完了前导数为0遇到了小数点,就意味着该数小于1 s.erase(s.begin()); //去掉小数点while(s.length()>0&&s[0]=='0'){//再去前导数为0的数,但是由于是在小数点之后,每去掉一个前导数是0,e也就是指数要减一 s.erase(s.begin());e--; } }//理解为小于1的深度搜索 else{ //如果去掉前导数后不是小数点,意味着大于1 while(k<s.length()&&s[k]!='.'){ //寻找小数点,在寻找过程中呢,记录下小数点的位置和经过的数位(有利于得到指数) k++;e++;} if(k<s.length()){ //为什么是k<s.length时有小数点,因为如果 k==s.length时,就是k到最后也没找到小数点 s.erase(s.begin()+k); //把小数点删掉 ,目的是循环输出的时候不用判断小数点了 } //可以理解为大于1的深度搜索 }if(s.length()==0){//如果删除前导零后,s的长度是0,也就是这个数是0,综上:这是在处理前导零遇到的三种情况 ,分别是去掉前导零后大于1,小于1和等于0,三种情况 e=0; } int num=0;k=0;string res;while(num<n){//n这里是全局变量 if(k<s.length()) res += s[k++]; //只要还有数字就加到末尾else res += '0';//前面的数不够有效位数的,补零num++; } return res; }int main(){string s1,s2,s3,s4;cin>>n>>s1>>s2;int e1=0,e2=0;s3=deal(s1,e1);s4=deal(s2,e2);if(s3==s4&&e1==e2){ cout<<"YES 0."<<s3<<"*10^"<<e1<<endl;} else{ cout<<"NO 0."<<s3<<"*10^"<<e1<<" 0."<<s4<<"*10^"<<e2<<endl;} return 0; }

 

总结

以上是生活随笔为你收集整理的【PAT】A1060 Are They Equal *的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。