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