PAT1060它们是否相等

感谢松鼠爱葡萄

大佬代码太简洁了ilil

#include <iostream>
#include <cstring>

using namespace std;

string change(string a, int n)
{
//    找到小数点的位置,从0开始计数
    int k = a.find(".");
//    如果字符串中没有 ".",在末尾给它加上一位 "."
    if (k == -1) a += '.', k = a.find(".");

//    去除 ".",做成一个新的字符串s
    string s = a.substr(0, k) + a.substr(k + 1);
//    去除前导0
    while (s.size() && s[0] == '0') s = s.substr(1), k -- ;

//    如果字符串为空 代表s="0"
    if (s.empty()) k = 0;
//    字符串长度比要求保留的位数要多, 则进行截取操作
    if (s.size() > n) s = s.substr(0, n);
//    否则 在末尾补0
    else s += string(n - s.size(), '0');

    return "0." + s + "*10^" + to_string(k);
}

int main()
{
    int n;
    string a, b;
    cin >> n >> a >> b;

    a = change(a, n);
    b = change(b, n);

    if (a == b) cout << "YES " << a << endl;
    else cout << "NO " << a << ' ' << b << endl;

    return 0;
}

科学计数法底数是0~1 

错误思路

我是想分类讨论,判断小数点位置与第一位不为0的点的距离之差,作为指数,然后再根据题目所需,取字符串中的指定长度,然后再加个小数点,还要在判断是不是要填充0……累。

实际上不需要这么麻烦,在原来的字符串上进行编辑

指数的判断:先找到原来小数点在的位置k,然后去掉小数点,每去掉一个前导0,k--,䒑太妙了

大佬的代码devc++硕tostring未declare,参考Dev C++ 报错: ‘to_string‘ was not declared in this scope_str' was not declared in this scope-CSDN博客

在tool里面加上一行并打钩ok

string新用法开发

string(n,'单个字符')

表示生成一个有

 string(3,'c') => "ccc"

必须是字符,不能是字符串

//修改后的ac
#include <cstdio>
#include <queue>
#include <vector> 
#include <set> 
#include <string>
#include <iostream>
#include <map>
using namespace std;
int point1,point2,n;
string anstr(string str)
{
	int k=str.find(".") ;
	//如果没有小数点,就加上小数点
	if(k==-1) str+=".",k=str.find(".");
	
	//去掉小数点
	str.erase(k,1);
//	cout<<str;
	//开始去前导
	while(!str.empty() && str[0]=='0')
	{str=str.substr(1);k--;
	//substr只提供一个参数,表示省略第二个参数,即py中的【3:】 
	//k就是指数 
	 } 
	 if(str.empty() ) k=0;
	 //接下来根据要求的字符长度,截断或填充
	 //截断 
	 if(str.size() > n)
	 str=str.substr(0,n);  
	 //填充
	 if(str.size() <n)
	 str=str+string(n-str.size() ,'0');
	 
	 
	 //+前缀 
	 str="0."+str;
	 str=str+"*10^"+to_string(k)  ;
	 
	 return str;
	
	
}

int main()
{string s1,s2,ans1,ans2;int first1,first2,e1,e2;
	cin>>n>>s1>>s2;
	int n1=s1.size() ;
	int n2=s2.size() ;
	point1=(s1.find(".")!=string::npos )? s1.find("."):-1;
	point2=(s2.find(".")!=string::npos )? s2.find("."):-1;
	if(anstr(s1)==anstr(s2))cout<<"YES"<<" "<<anstr(s1);else cout<<"NO"<<" "<<anstr(s1)<<" "<<anstr(s2);
	
	

 } 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值