欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

【科学计数法模板讲解】1060 Are They Equal (25 分)

发布时间:2024/2/28 38 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【科学计数法模板讲解】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 分)的全部内容,希望文章能够帮你解决所遇到的问题。

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