1060 Are They Equal (25分)
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
一开始写一堆错。。就对了前面4个点,一堆坑,,
综合了一下网友们的测试点,这些测试点都过了,那么也就过了:
2 0.0015 0000.001520000
YES 0.15*10^-2
3 010.25 0010.23
YES 0.102*10^2
5 0.1 00.100
YES 0.10000*10^0
10 000.0012 0000000.0012000000000
YES 0.1200000000*10^-2
3 0 0.000
YES 0.000*10^0
原文链接:https://blog.csdn.net/qq_40875849/article/details/101257333
4 00034.5 0.00345
2 0.0 0.001
1 0.1 1.0
5 0 00.0
原文链接:https://blog.csdn.net/qq_40438165/article/details/99776511
我自己分的情况有点复杂,不太方便细说,大概的讲一下,代码里的c表示的是小数点.的index,我先把给的float前面的后面的多余的0都去掉,然后分了3种情况来计算 前面的小数部分和 10的指数部分。最后的话不足k位的小数部分末尾补下0就好了
代码:
#include<iostream>
using namespace std;
int getC(string x){ //返回.的index
int c = 0;
while (c < x.size()&&x[c]!='.')
c++;
return c;
}
string floatToSpecial(string x,int k){
int c = getC(x);
//使用substr(index)去除最前面多余的0
int significant = 0;
if(c>1){
while(x[significant]=='0'){
significant++;
}
if(significant==c){
significant--;
}
x = x.substr(significant);
}
c = getC(x);
//使用substr(0,l)去除小数点后面多余的0
int index = x.size() - 1, l = 0;
while(c<index&&x[index]=='0'){
index--;
l++;
}
x = x.substr(0, x.size() - l);
c = getC(x);
int zhishu = c;
string pre = "";
if(x[0]=='0'){
c++;
zhishu = 0;
while(c<x.size()&&x[c]=='0'){
c++;
zhishu--;
}
for (int i = 0; i < k && c < x.size();i++,c++){
pre += x[c];
}
}else if(c<k&&c>0&&x[0]!='0'){
for (int i = 0; i < k+1 && i < x.size();i++)
if(x[i]!='.'){
pre += x[i];
}
}else if(c>=k){
for (int i = 0; i < k && i < x.size(); i++){
pre += x[i];
}
}
//不足k位的话末尾补0
int num = k - pre.size();
for (int i = 0; i < num;i++){
pre += '0';
}
return "0." + pre + "*10^" + to_string(zhishu);
}
int main(){
string a, b;
int k;
cin >> k >> a >> b;
string an1 = floatToSpecial(a, k), ans2 = floatToSpecial(b, k);
int flag = an1 == ans2;
if(flag){
cout << "YES" << " " << an1;
}else{
cout << "NO" << " " << an1 << " " << ans2;
}
return 0;
}