pat解題報告【1073】

1073. Scientific Notation (20)

時間限制  
100 ms
內存限制  
32000 kB
代碼長度限制  
16000 B
判題程序    
Standard    
作者    
HOU, Qiming

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 file 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

 

這題本質是模擬科學計數法的轉換,坑在這句話:The number is no more than 9999 bytes in length,什麼意思呢,這個數的位數可以很長!剛開始沒注意這句話,把字符串轉換成數字,做計算。結果最後兩個點過不了,仔細看了看發現題目裏有這句話。改成字符串模擬計算過程的算法,ac了。

代碼:

// pat-1073.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"

#include "iostream"
#include "string"
#include "stdio.h"
#include "vector"
#include "fstream"

using namespace std;
vector<char> ans_pre;
vector<char> ans_apend;

int main()
{
	//+1.23400E-03
	//shishu:1.23400 zhishu:03
	//op:+ dir:-
	fstream fcin;
	fcin.open("C:\\Users\\Administrator\\Desktop\\456.txt");
	string str;
	fcin>>str;

	int offset=str.find('E');
	string shishu=str.substr(1,offset-1);//實數部分 
	int shishu_l=shishu.length();//實數的長度

	char op=str[0];
	char dir=str[offset+1];

	int offset2=str.length()-1-offset-1;
	string expart=str.substr(offset+2,offset2);
	double zhishu=atof(expart.c_str());
	int apend=0;
	int pos=0;//原始小數點位置 
	if (dir=='-')
		pos-=zhishu;
	else
		pos+=zhishu;
	if (pos<0)
	{	
		while(pos<0)
	   {
		ans_pre.push_back('0');
		pos++;
	  }

	}
	else
	{   
	    apend=pos-(shishu_l-2);//小於0說明還是有小數位的
		while(apend>0){
			ans_apend.push_back('0');
			apend--;
		}
	}
	int index=shishu.find('.');
	shishu.erase(index,1);

	if (apend<0)//移動小數點
	{
		shishu.insert(shishu_l-1+apend,".");
	}

	if (op=='-')
	{
		cout<<'-';
	}
    if (!ans_pre.empty())
    {
		cout<<ans_pre.back();
		ans_pre.pop_back();
		cout<<".";
		while(!ans_pre.empty())
		{   
			cout<<ans_pre.back();
			ans_pre.pop_back();
		}
		
    }

	cout<<shishu;
	while(!ans_apend.empty())
	{
		cout<<ans_apend.back();
		ans_apend.pop_back();
	}
		return 0;
}


這個題目裏有些字符串處理函數,可以仔細研究研究。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章