PAT (Advanced Level) Practice 1073 Scientific Notation (20 分) 凌宸1642

PAT (Advanced Level) Practice 1073 Scientific Notation (20 分) 凌宸1642

题目描述:

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.

译:科学计数法是科学家用来表示很大或很小的数字的一种方便的方法,其满足正则表达式 [+-][1-9].[0-9]+E[+-][0-9]+ ,即数字的整数部分只有 1 位,小数部分至少有 1 位,该数字及其指数部分的正负号即使对正数也必定明确给出。

现以科学计数法的格式给出实数 A,请编写程序按普通数字表示法输出 A,并保证所有有效位都被保留。


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.

译:每个输入包含 1 个测试用例,即一个以科学计数法表示的实数 A。该数字的存储长度不超过 9999 字节,且其指数的绝对值不超过 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.

译:对每个测试用例,在一行中按普通数字表示法输出 A,并保证所有有效位都被保留,包括末尾的 0。


Sample Input 1 (样例输入 1 ):

+1.23400E-03

Sample Output 1 (样例输出 1 ):

0.00123400

Sample Input 2 (样例输入 2 ):

-1.2E+10

Sample Output 2 (样例输出 2 ):

-12000000000

The Idea:

科学计数法其实就是整数部分只有一位有效数字,我们可以根据这个性质,先把符号搞定;然后根据指数的符号确定是需要扩大多少倍还是缩小多少倍。所以我们需要得到小数点后面的有效数字有多少位,以及指数的大小。根据两者的比较来进行输出的龙控制,详情看代码注释,每一步都写得很清楚啦。

The Codes:

#include<bits/stdc++.h>
using namespace std;
string in ;
int main(){
	getline(cin , in) ;
	if(in[0] == '-') cout << "-" ; // 如果是负数,先输出负号 
	int dot , e ;
	for(int i = 1 ; i < in.size() ; i ++){
		if(in[i] == '.') dot = i ; // 记录小数点 . 的位置 
		if(in[i] == 'E') e = i ; // 记录指数 E 的位置
	}
	int mid = e - dot - 1 , tail = 0 ; // mid 表示中间有效位数的位数 
	for(int i = e + 2 ; i < in.size() ; i ++)
		tail = tail *10 + (in[i] - '0'); // 记录指数的大小 
	if(in[e + 1] == '-'){ // 如果指数的指数是负的,说明是小数
		cout<<"0." ; // 先输出 0. 
		for(int i = 0 ; i < tail - 1 ; i ++) cout << "0" ; // 输出指数大小个 0  
		cout << in[1] ; // 输出第一位有效数字 
		for(int i = 3 ; i < 3 + mid ; i ++) cout << in[i] ; // 输出中间的有效数字 
	}else{ // 指数是正的  
		cout<< in[1] ;   // 先输出第一位有效数字
		if(mid > tail){ // 如果中间的有效位数的个数大于指数的大小 
			for(int i = 3 ; i < 3 + tail ; i ++) cout<<in[i] ; // 先扩大相应的倍数 
			cout<<"." ; // 输出小数点 
			for(int i = 3 + tail ; i < 3 + mid ; i ++) cout<<in[i] ; // 输出剩余的有效数字 
		}else{
			for(int i = 3 ; i < 3 + mid ; i ++) cout<<in[i] ;  // 输出所有的有效数字
			for(int i = mid ; i < tail ; i ++) cout<<"0" ;  // 输出后补 0  
		}
	}
	return 0 ;
}

posted @ 2021-04-12 00:21  凌宸1642  阅读(54)  评论(0编辑  收藏  举报