PAT (Advanced Level) Practice 1060 Are They Equal

柔光的暖阳◎ 2023-06-24 11:24 117阅读 0赞

这题可以分两部,先求出要保留的数字部分,再求出指数部分,另外浮点数作为字符串处理时,一定要考虑前导0和末尾0,例如:000.00,0099.800。

给出一组比较容易错的数据:4 0000 0000.00 // YES 0.0000*10^0

  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <string>
  4. using namespace std;
  5. string chop(string str, int n){//获取有效数据
  6. string result = str;
  7. int index = result.find(".");
  8. if(index != string::npos){
  9. result.erase(index,1);
  10. }
  11. while(result.length()>1 && result[0]=='0'){
  12. result.erase(0,1);
  13. }
  14. while(result.length() > n){
  15. result.erase(result.length()-1,1);
  16. }
  17. while(result.length() < n){
  18. result += "0";
  19. }
  20. return result;
  21. }
  22. int getP(string str){//获取指数
  23. string result = str;
  24. while(result.length()>2 && result[0]=='0' && result[1]!='.'){
  25. result.erase(0,1);
  26. }
  27. int index = result.find(".");
  28. if(index ==string::npos){
  29. if(result[0]=='0'){
  30. return 0;
  31. }else{
  32. return result.length();
  33. }
  34. }else{
  35. if(result[0]=='0'){
  36. int m = 0;
  37. while(index+1<result.length() && result[index+1]=='0'){
  38. m--;
  39. index++;
  40. }
  41. if(index+1>=result.length()){
  42. return 0;
  43. }else{
  44. return m;
  45. }
  46. }else{
  47. return index;
  48. }
  49. }
  50. }
  51. int main()
  52. {
  53. int n,len_a,len_b;
  54. string a,b;
  55. cin>>n>>a>>b;
  56. len_a = a.length();
  57. len_b = b.length();
  58. int pa,pb;//计算a b是十的多少次方
  59. pa = getP(a);
  60. pb = getP(b);
  61. string ra=chop(a,n);
  62. string rb=chop(b,n);
  63. if(ra == rb && pa == pb){
  64. cout<<"YES"<<" "<<"0."<<ra<<"*10^"<<pa<<endl;
  65. }else{
  66. cout<<"NO"<<" "<<"0."<<ra<<"*10^"<<pa<<" "<<"0."<<rb<<"*10^"<<pb<<endl;
  67. }
  68. return 0;
  69. }

发表评论

表情:
评论列表 (有 0 条评论,117人围观)

还没有评论,来说两句吧...

相关阅读