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×1050.123\times 10^50.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 NNN, AAA and BBB, where NNN (<100<100<100) is the number of significant digits, and AAA and BBB are the two float numbers to be compared. Each float number is non-negative, no greater than 1010010^{100}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
代码:
#include <iostream>
#include <string>
using namespace std;
//注释看不懂不要来问我,我看得懂就行了,(#^.^#)
int n; //有效位数
string deal(string s,int& e){
//这里的e使用的是引用类型,一定要注意!!!!!!!
int k = 0; //小数点前面的位数指针下标
//去掉小数点前面多余的0
while(s.length() > 0 && s[0]=='0'){
s.erase(s.begin());
}
if(s[0] == '.'){
//去掉前面多余的0后只剩小数点:s为小于1的小数
s.erase(s.begin());
while(s.length() > 0 && s[0]=='0'){
s.erase(s.begin());
e--;
}
}else{
//去掉前面多余的0后不只剩小数点:s大于1
//找到小数点并删除,同时记录位数
while(s[k] != '.' && k < s.length() ){
k++;
e++;
}
if( k < s.length()){
//k!= s.length()说明输入的数不是整数,而是有小数点
//去掉小数点
s.erase(s.begin() + k);
}
}
if(s.length() == 0){
e = 0;
}
/*
到这里为止,e就已经确定下来了
s已经筛选好了,等待下一步的处理
*/
int num = 0; //记录位数(与精度的关系
k = 0; // 字符串中的指针位数
string res ; //用来保存处理好的字符串结果并返回
while(num < n){
if( k < s.length() )
res = res + s[k++];
else
res = res + '0';
num ++;
}
return res;
}
int main(){
string s1, s2, s3, s4;
cin >> n >> s1 >> s2;
int e1 = 0, e2 = 0;
s3 = deal(s1,e1);
s4 = deal(s2,e2);
//注意严格的输出格式要求!
if(s3 == s4 && e1 == e2){
cout<<"YES 0."<<s3<<"*10^"<<e1<<endl;
} else {
cout<<"NO 0."<<s3<<"*10^"<<e1<<" 0."<<s4<<"*10^"<<e2<<endl;
}
return 0;
}
总结:
- Tips:编译器一定要记得改成C++(g++),不然会一直报编译错误!
- 在处理复杂的数字问题时,转换成string来进行增删改查,可行性会高很多。
- string 类型使用 cin、cout来输入输出
- 一定要记得加上头文件和命名空间(忘记很多次啦!)
#include <iostream>
#include <string>
using namespace std;
Coding。。。。。。