1073 Scientific Notation (20 分)字符串处理——科学计数法

题目

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

解题思路

  题目大意: 给一个使用科学计数法表达的数,然后将概述转换成普通表达方式,该数据小数点后必有一位,数据格式为[±][1-9].[0-9]+E[±][0-9]+,要求保留数据有效位。
  解题思路: 数据位的长度最长为9999,显然需要用字符串来处理,而不是任何浮点型。由于题目给出了明确的数据格式,因此,根据字符串定义格式,以及科学计数法的定义去还原数据即可——
  1. 第一位记录正负值,负值需要在结果前加“-”符号,正值不需要加“+”;
  2. 第二位到E之间的数据是数据的有效位,除去小数点,统计即可;
  3. E后第一位是系数的正负值,该值决定了小数点往左移还是往右移;
  4. 最后几位是系数,取出来转换成整型即可。
  在字符串处理完之后,根据获取的有效位和系数进行还原即可。

/*
** @Brief:No.1073 of PAT advanced level.
** @Author:Jason.Lee
** @Date:2019-01-21
** @Solution: Accepted!
*/
#include
#include
#include
using namespace std;

char input[10000];


int main(){
	while(cin>>input){
		int postive = (input[0]=='+'?1:-1);
		int index = 1;
		string number;
		while(input[index]!='E'){
			if(input[index]!='.') number+=input[index];
			index++; 
		}
		int exp_pos = (input[++index]=='+'?1:-1);
		int exp = 0;
		index++;
		while(input[index]){
			exp=exp*10+(input[index++]-'0');
		}
		//cout<<"frac = "<
		//cout<<"exp = "<
		string res;
		if(exp==0){
			res = number;
			res.insert(1,".");
		}else if(exp_pos==1){
			res = number;
			int zeros = (exp-(number.length()-1));
			if(zeros>=0){
				while(zeros--){
					res+="0";
				}
			}else{
				zeros=exp+1;
				res.insert(zeros,".");
			}
		}else{
			res = "0.";
			while(--exp){
				res+="0";
			}
			res+=number;
		}
		if(postive<0) res = "-"+res;
		cout<<res<<endl;
	}
	return 0;
} 

1073 Scientific Notation (20 分)字符串处理——科学计数法_第1张图片

总结

  这道题其实挺难的,尤其是我最开始忘记了科学计数法的定义了,即便是知道了定义,总结规律然后去写程序也花了一点时间。这道题用string来处理,会省很多事,无奈string用的不是很溜,几个成员函数用得不对,结果错了。最后采用了string和char数组混编的方式,有点奇葩。

你可能感兴趣的:(PAT,1073,字符串处理,PAT-Advanced,Level)