目录
题目
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
思路
难度评级:⭐️⭐️
1. 先去小数点
比如123.456变成123456*10^3
2. 再整数保留n位(比如n为3时)
即123456*10^3变成123*10^3
3. 最后确定次方数
即123*10^3中123为格式化后的小数部分,次方数由3变为3+n=6,最终为0.123*10^6
C++ 知识点UP
1. vector判断是否相等
vector相等是指容器内值和顺序都一致
可以直接用vec1==vect2这种方式去判断
2. 指针类型变量所指地址改值(注意*优先级)
比如:指针类型变量power所指地址的值需要+1时,不可以直接*power++,而要对*power加括号,即(*power)++,因为*的优先级低于++的优先级
代码
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int n;
vector<char> formatFloat(string str,int* power) {
vector<char> res;
// 先去小数点(eg.将123.456变成123456*10^-3)
bool isBegin=true;
bool afterPot=false;
(*power)=0;
for(int i=0;i<str.size();i++) {
// 舍弃掉开头连续的0
if(isBegin&&str[i]=='0') {
// 小数点后的0在舍弃时,power要变小
if(afterPot) (*power)--;
continue;
}
// 遇到小数点时
if(str[i]=='.') {
afterPot=true;
}else {
// 遇到数字时
res.push_back(str[i]);
if(afterPot) (*power)--;
isBegin=false;
}
}
// 这个数就是0时
if(isBegin) {
res.push_back('0');
*power=0;
}
// 计算整数部分只保留n位时的情况(eg.123456*10^-3变成123*10^-3)
int diff=res.size()-n;
if(!isBegin) (*power)+=diff;
for(int i=0;i<abs(diff);i++) {
if(diff>0) res.pop_back();
else if(diff<0) res.push_back('0');
}
// res记录小数部分,power记录题目要求的format形式中的次方数
if(!isBegin) (*power)+=n;
return res;
}
void printFormat(vector<char> vec, int power) {
cout<<" 0.";
for(int i=0;i<n;i++) {
cout<<vec[i];
}
cout<<"*10^"<<power;
}
int main(int argc, char** argv) {
string a,b;
cin>>n>>a>>b;
int powerA,powerB;
vector<char> aFormat=formatFloat(a,&powerA);
vector<char> bFormat=formatFloat(b,&powerB);
// 判断a b是否相等
if(powerA==powerB&&aFormat==bFormat) {
cout<<"YES";
printFormat(aFormat,powerA);
}else {
cout<<"NO";
printFormat(aFormat,powerA);
printFormat(bFormat,powerB);
}
return 0;
}