题目
题目地址:
https://pintia.cn/problem-sets/994805342720868352/problems/994805413520719872
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.12310^5
Sample Input 2:
3 120 128
Sample Output 2:
NO 0.12010^3 0.128*10^3
代码
这道题让我熟悉了string方法的使用,我收获很多,虽然花了近两个小时。
#include <iostream>
#include <string>
#include <stdio.h>
#include <set>
#include<string>
using namespace std;
//对str进行修改,使其位数为N
bool Get_reg_digits(string &str,int N) {
while (str.size() < N) //有效数字缺0
str = str + "0";
str.erase(N , str.size() - N); //有效数字过多
if (str[0] == '0') //全为0
return false;
else
return true;
}
//将str修改为科学计数法的有效数字,e为输出科学计数法指数,N为有效数字
void deal(string &str, int N, int &e) {
string str_out;
int i = 1;//i=1,输出调试值
//去掉前导零
while ( str[0] == '0' && str.size()>1)
str.erase(str.begin());
//确定指数
e = str.find(".");
//没有小数点,形如"32500"
if (e == string::npos)
{
e = str.size();
if(Get_reg_digits(str, N)==false){
e = 0;
}
return;
}
//形如".a"
if (str[0] == '.') {
str.erase(e, 1); //删除'.'
//去掉前导零
while (str[0] == '0' && str.size() > 1) {
str.erase(str.begin());
e--;
}
if (Get_reg_digits(str, N) == false) {
e = 0;
}
return;
}
//形如"a.b"的情况
str.erase(e, 1); //删除'.'
Get_reg_digits(str, N);
return;
}
int main() {
int N;
cin >> N;
string str1,str2;
cin >> str1 >> str2;
//输出元素,指数e
int e1=0,e2=0;
deal(str1, N, e1);
deal(str2, N, e2);
if (str1==str2 && e1==e2) {
cout << "YES " << "0."<< str1 << "*10^" << e1 << endl;
}
else {
cout << "NO " << "0." << str1 << "*10^" << e1 << " ";
cout << "0." << str2 << "*10^" << e2 << endl;
}
return 0;
}