原题
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×105 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 10100 , 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
大体题意
判断两个数的科学计数法是否相同,省略到三个小数
思路
主要就是将浮点数转化为科学技术法的形式然后判断二者是否相同
因此设置结构体(底数和指数)
重点就是如何转换成科学技术法
浮点数用string读入
首先去除前面的0,去除后判断第一位是否是小数点
如果是小数点则a是小于1的数:
小数点后面连续0的个数即为数的指数的负数
例如:0.00123 ->0.123 指数为-2
如果不是小数点,则a是大于等于1的数
那么小数点前面的数的个数就是数的指数
例如:12.30 -> 0.123 指数为2
这样指数的数值就确立了
接下来是底数,底要求是非0开头的长度为3的字符串。此时的底已经和小数点没有关系了,但是要注意当字符串的长度不足时要在后面补0
例如:12 -> 0.120 指数为2
注意点:在判断好指数后,需要观察剩下的字符串是否为0,如果为0,那么指数也是0。不为0再进行底数的处理
具体看PAT相关的基础知识
最后如果二者相等则只需输出一个结果,如果二者不等,则两个都要输出
代码
#include <iostream>
#include <string>
using namespace std;
const int max_n = 110;
struct science_num {
string di;
int zhi;
} na, nb;
science_num change(string a, int N) {
int k = 0;
science_num na;
na.zhi = 0;
na.di.clear();
//去除前导0
while (a.length() > 0 && a[0] == '0') {
a.erase(a.begin());
}
//若a是小于1的数
if (a[0] == '.') {
a.erase(a.begin());
while (a.length() > 0 && a[0] == '0') {
a.erase(a.begin());
na.zhi--;
}
}
//若a不小于,找到可能存在的小数点并删除
else {
while (k < a.length() && a[k] != '.') {
k++;
na.zhi++;
}
if (k < a.length()) {
a.erase(a.begin() + k);
}
}
//若a为0,将其置0
if (a.length() == 0) {
na.zhi = 0;
}
//预处理完毕,规格化
if (a.length() >= N) {
na.di.insert(na.di.begin(), a.begin(), a.begin() + N);
}
else {
na.di.insert(na.di.begin(), a.begin(), a.end());
for (int i = 0; i < N - a.length(); i++) {
na.di += '0';
}
}
return na;
}
int main() {
int N;
string a, b;
cin >> N >> a >> b;
na = change(a, N);
nb = change(b, N);
if (na.di == nb.di && na.zhi == nb.zhi) {
cout << "YES 0." << na.di << "*10^" << na.zhi;
}
else {
cout << "NO 0." << na.di << "*10^" << na.zhi << " 0." << nb.di << "*10^" << nb.zhi;
}
return 0;
}