PAT-A 真题 – 1073 Scientific Notation

发布于 / PAT-甲级 / 0 条评论

Scientific notation is the way that scientists easily handle very large numbers or very small numbers. The notation matches the regular expression [+-][1-9].[0-9]+E[+-][0-9]+ which means that the integer portion has exactly one digit, there is at least one digit in the fractional portion, and the number and its exponent's signs are always provided even when they are positive.

Now given a real number A in scientific notation, you are supposed to print A in the conventional notation while keeping all the significant figures.

Input Specification:

Each input contains one test case. For each case, there is one line containing the real number A in scientific notation. The number is no more than 9999 bytes in length and the exponent's absolute value is no more than 9999.

Output Specification:

For each test case, print in one line the input number A in the conventional notation, with all the significant figures kept, including trailing zeros.

Sample Input 1:

+1.23400E-03

Sample Output 1:

0.00123400

Sample Input 2:

-1.2E+10

Sample Output 2:

-12000000000

题目大意:给定科学记数法表示的数,转换成普通数字。注意精确位数不能变。

这道题没什么太大的技术含量,单纯的体力活。。。逻辑比较复杂,必须细心,我写了一个多小时才写出来,一遍AC。

作为一个语言表达能力很弱良心博主,注释写的比较清晰

#include <cstdio>
#include <iostream>
#include <string>
using namespace std;

int main(){
  string s, num;
  int e = 0;
  bool _e = true;  //指数的正负,true为+,false为负 
  cin >> s;
  if(s[0] == '-') cout << '-';
  bool in_e = false;
  for(int i = 1; i < s.length(); i++){
    if(s[i] == '.') continue;
    if(s[i] == 'E') {
      if(s[++i] == '-') _e = false;
      in_e = true;
      continue;
    }
    if(!in_e) num += s[i];  //没有读到过e,数据存入num 
    else e = e*10+s[i]-'0'; //读到了e,数据累加到e
  }
  //cout << num << endl << e << endl;
  if(_e){  //如果指数是正的
    int i = 0;
    for(; i <= e; i++){  //移动小数点 
      if(i < num.length()) //如果还输出完整个数字,则继续输出 
        cout << num[i];
      //如果输出完整个数字,并且还没完成移动小数点,输出0 
      if(i >= num.length() && i < e) cout << 0; 
    }
    if(i < num.length()) cout << '.'; //如果输出完数字了,说明小数点在这个位置 
    while(i < num.length()) cout << num[i++]; //没输出完整个数字,继续输出 
    while(i < e){ //如果尚未到达要求移动的位数,输出0 
      cout << 0;
      i++;
    }
    if(i != num.length()) cout << 0;//防止只输出了一个小数点,不输出0 
  }else{  //指数是负的 
    if(e) cout << "0."; //指数非0,输出0.
    for(int i = 1; i < e; i++) cout << 0; //在移动范围内,输出0 
    for(int i = 0; i < num.length(); i++) cout << num[i]; //最后把整个数字输出即可 
  }
  return 0;
}

转载原创文章请注明,转载自: 斐斐のBlog » PAT-A 真题 – 1073 Scientific Notation
目前还没有评论,快来抢沙发吧~