【科学计数法模板讲解】1060 Are They Equal (25 分)
立志用最少的代碼做最高效的表達
PAT甲級最優題解——>傳送門
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
科學計數法計算邏輯:
1、找小數點位置。
2、找某數第一個不為0數字的位置。
3、將第一個不為0數字后的數字加入temp(有效數字)
4、第二點減第一點為指數值
5、判斷指數和有效數字是否相等即可。
小傻瓜們還在苦苦寫模擬, 而大lao們早就用上了模板~
#include<bits/stdc++.h> using namespace std;int f(const string&s, string&temp, int N) {int point = s.size(), index = -1; //小數點位置、第一個非0數字位置for(int i = 0; i < s.size(); i++) {if(s[i] == '.') //找小數點 point = i;//若第一個不為0的位置找到,則將其后的數字加入temp else if(index != -1 && temp.size() < N) temp += s[i];else if(index == -1 && s[i] != '0') { //找第一個不為0的位置 index = i;temp += s[i];}} while(temp.size() < N) //如果temp長度小于N,那么+0temp += "0";if(index == -1) //沒有找到非零數字,說明字符串s表示的數是0return 0; point -= index; //小數點減去第一排非零數字位置得到指數 return point < 0 ? point+1 : point; //如果為負數,返回point+1,否則返回point }int main() {int N;string A, B, Atemp="", Btemp="";cin >> N >> A >> B; //讀取數據int Aexp = f(A, Atemp, N), Bexp = f(B, Btemp, N); if(Aexp == Bexp && Atemp == Btemp) //若有效數字和指數皆相同cout << "YES 0." << Atemp << "*10^" << Aexp;else cout << "NO 0." << Atemp << "*10^" << Aexp << " 0." << Btemp << "*10^" << Bexp; return 0; }
耗時:
求贊哦~ (?ω?)
總結
以上是生活随笔為你收集整理的【科学计数法模板讲解】1060 Are They Equal (25 分)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【解决办法】你目前是以 ***的身份登录
- 下一篇: 【最详细的分析】1061 Dating