1. 程式人生 > >PAT A1073 Scientific Notation (20 分)——字符串轉數字

PAT A1073 Scientific Notation (20 分)——字符串轉數字

nbsp ber test ros num ecif 情況 opened algo

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
#include <stdio.h> 2 #include <map> 3 #include <algorithm> 4 #include <iostream> 5 #include <string> 6 #include <math.h> 7 using namespace std; 8 9 int main(){ 10 string a; 11 cin >> a; 12 if (a[0] == -){ 13 printf("-"); 14 a.erase(0, 1); 15 } 16 else if (a[0] == +){ 17 a.erase(0, 1); 18 } 19 a.erase(1, 1); 20 int pos_e; 21 pos_e = a.find(E); 22 string sub_str = a.substr(pos_e + 1, a.length() - pos_e - 1); 23 int flag = 1; 24 if (sub_str[0] == -)flag = -1; 25 a.erase(pos_e, 1 + sub_str.length()); 26 sub_str.erase(0, 1); 27 while (!sub_str.empty() && sub_str[0] == 0){ 28 sub_str.erase(0, 1); 29 } 30 int exp = 0; 31 if (sub_str.empty())exp = 0; 32 else{ 33 for (int i = 0; i < sub_str.length(); i++){ 34 exp = exp * 10 + sub_str[i] - 0; 35 } 36 } 37 int extra = 0; 38 if (flag == -1){ 39 for (int i = 0; i < exp - 1; i++){ 40 a.insert(0, "0"); 41 } 42 a.insert(0,"0."); 43 } 44 else{ 45 int l = a.length(); 46 47 if (exp >= l - 1){ 48 for (int i = 0; i < exp - l+1;i++){ 49 a.insert(a.length(),"0"); 50 } 51 52 } 53 else{ 54 a.insert(1 + exp, "."); 55 } 56 } 57 cout << a; 58 system("pause"); 59 }
View Code

註意點:和B1024一樣,就是分情況實現,字符串轉數字,要記得字符串的find,erase,substr操作。

PAT A1073 Scientific Notation (20 分)——字符串轉數字