1. 程式人生 > >1073 Scientific Notation(字串處理)

1073 Scientific Notation(字串處理)

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

分析

此處考察字串的處理
注:本題在第一次提交時測試點4(從0開始計數)一直通不過,最後再檢視if語句的邊界條件是發現邊界判斷條件出錯,測試點4測試的是當指數為正整數時,此時要考慮若原有的小數位位數比指數小則要考慮在尾部追加0,然後再確定小數點’’.'的位置,測試點4考察當小數位數大於指數,小數點位數是否正確。在做條件判斷時候,一定要考慮清楚邊界條件,這個往往是測試點。

#include <iostream>
#include <cmath>
using namespace std;
int main() {
	string s;
	cin>>s;
	int flag=s[0]=='-'?-1:1;
	s.erase(0,1);
	int k=2; 
	while(k<(int)s.length() && s[k]!='E') k++;
	int flag2=s[k+1]=='-'?-1:1;
	string c=s.substr(0,k).erase(1,1),e=s.substr(k+2,s.length());
	int e_num=0;
	for(int i=0; i<(int)e.length(); i++) {
		e_num += (e[i]-'0')*pow(10,e.length()-i-1);
	}
	if(e_num!=0) {
		if(flag2<0) {
			for(int i=0; i<e_num; i++)
				c.insert(0,"0");
			c.insert(1,".");
		} else if(flag2>0) {
			int len_c=c.length();
			for(int i=0; i<e_num-len_c+1; i++) {
				c.push_back('0');
			}
			if(e_num<len_c-1) c.insert(e_num+1,".");
		}
	}else{
		c.insert(1,".");
	}
	if(flag<0) c.insert(0,"-");
	cout<<c;
	return 0;
}