解题过程的小记录,如有错误欢迎指出。
难度:三星(简单题但需要考虑的方面很多,特别是数字前有0真的没想到orz)
题目分析
给出两个数,看它们在保留某一相同位数的科学进制法下是否完全一致
注意点
- 需要考虑前面含有0的数字,如00123,000.123之类
- 不考虑四舍五入
我的解题过程
思路
- 将输入的两个数用string保存
- 写一个chopping函数返回转化为要求输出的字符串
- 在chopping函数中,先去除开头多余的0(如00123),再按是否开头为‘0’以及是否含有小数点分类讨论
- 将两个数用chopping返回的字符串进行比较,看是否一致
bug
这题因为要考虑的方面很多,所以边测试边写,特别要注意0的输出问题(如0,0.00)
不过真的没想到如00123和00.000的数字写法,所以报错了两个测试点
代码
#include<iostream>
#include<string>
using namespace std;
int n;
string chopping(string num) {
string result = "0.";
while (num[0] == '0'&&num[1] != '.'&&num.size() > 2) {
num = num.substr(1);
}
if (num[0] == '0') {
if (num.find(".") == string::npos) {
int t = n;
while (t != 0) {
result += "0";
t--;
}
result += "*10^0";
return result;
}
else {
int pos = 2;
while (num[pos] == '0'&&pos < num.size()) pos++;
if (pos == num.size()) {
int t = n;
while (t != 0) {
result += "0";
t--;
}
result += "*10^0";
}
else {
if(num.substr(pos).size()>=n)
result += num.substr(pos, n);
else {
result += num.substr(pos);
int t = n - num.substr(pos).size();
while (t-- != 0) result += "0";
}
result += "*10^";
if (pos > 2) result += "-";
result += to_string(pos - 2);
}
}
}
else {
if (num.find(".") == string::npos) {
if (num.size() >= n) result += num.substr(0, n);
else {
result += num;
int t = n - num.size();
while (t-- != 0) {
result += "0";
}
}
result += "*10^";
result += to_string(num.size());
}
else {
int pos = num.find(".");
num.erase(num.begin() + pos);
if(num.size()>=n) result += num.substr(0, n);
else {
result += num;
int t = n - num.size();
while (t-- != 0) {
result += "0";
}
}
result += "*10^";
result += to_string(pos);
}
}
return result;
}
int main()
{
string a, b;
//n = 4;//测试用
//cout << chopping("00.000") << endl;//测试用
cin >> n >> a >> b;
if (chopping(a) == chopping(b)) cout << "YES " << chopping(a);
else cout << "NO " << chopping(a) << " " << chopping(b);
return 0;
}
dalao的代码
全部代码因版权原因不放出来,大家可以自行去柳神博客购买或者参考晴神的上机笔记~
借鉴点
- 去掉前导0的时候可以把在小数点前的所有0都去掉,这样如果num[0]是小数点的话说明是小于1的数
- 本题每个人的思考方式不一样,在考虑全面的情况下,用自己习惯的就好,适应别人的太累,为了考虑全面最好背一下科学计数法容易出错的几个点(000.0000,123.478,0.00123,00123.147),然后边做边进行测试