PAT 1073 Scientific Notation (20)

1073 Scientific Notation (20)(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 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

 思路:

这道题是要我们把科学计数法的数字转化成一般数字,其实就是个控制输出格式。一共三种情况,如果E后面是负数,那么在数字前面补0.0……即可,如果E后面是正数,就要考虑末尾需不需要补0。

代码:

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <map>  
#include <set>
using namespace std;

int main()
{
	string s1, s2 = "";
	cin >> s1;
	if (s1[0] == '-')
	{
		s2 += '-';
		s1 = s1.erase(0, 1);
	}
	else if (s1[0] == '+')
		s1 = s1.erase(0, 1);
	s1 = s1.erase(1, 1);
	int pow = 0, mul = 1, i;
	for (i = s1.length()-1; i >= 0; i--)
	{
		if (s1[i] >= '0'&&s1[i] <= '9')
		{
			pow += (s1[i] - '0')*mul;
			mul *= 10;
		}
		else
			break;
	}
	if (s1[i] == '-')
	{
		pow *= -1;
		i--;
	}
	else if (s1[i] == '+')
		i--;
	s1 = s1.erase(i, s1.length() - i);
	if (pow < 0)
	{
		s2 += "0.";
		for (i = 0; i < abs(pow) - 1; i++)
			s2 += '0';
		s2 += s1;
	}
	else
	{
		if (pow >= s1.length() - 1)
		{
			s2 += s1;
			for (i = 0; i < pow - s1.length() + 1; i++)
				s2 += '0';
		}
		else
		{
			s1 = s1.insert(pow + 1, ".");
			s2 += s1;
		}
	}
	cout << s2 << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/ryo_218/article/details/81509028