【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.9Sample Output 1:
YES 0.123*10^5Sample Input 2:
3 120 128Sample 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 *的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【PAT】A1063 Set Simil
- 下一篇: 【2019暑假刷题笔记-STL绪论】总结