pat 科学记数法

问题分析:

首先用字符串存储输入,通过循环判断,首先将字符串分为两个部分,前面的 基数和后面的指数

引入substr() stoi()  分别表示取部分字符串,和将字符转化为数字

首位输出数字的正负

假若指数n<0;将小数点往左移动

若n>0;分类判断

1.基数的数字足够长,不用低位补零

2.基数不够,补零

#include<iostream>
#include<string>
using namespace std;


int main()
{
	string s;
	cin >> s;
	int i = 0;
	while (s[i] != 'E')
		i++;
	string t = s.substr(1, i - 1);//(开始,长度)前面的数字
	int n = stoi(s. substr(i + 1));//从第i+1个开始复制
	if (s[0] == '-')
		cout << "-";
	if (n < 0) {// 若指数小于零,小数点左移。
		cout << "0.";
		for (int j = 0;j < abs(n) - 1;j++) //移动的位数取决于指数绝对值得大小
			cout << '0';
		for (int j = 0;j < t.length();j++)
			if (t[j] != '.')  //除了小数点外输出所有基数
				cout << t[j];

	}
	else {
		cout << t[0];  //反之小数点右移
		int cnt, j;
		for (j = 2, cnt = 0;j < t.length() && cnt < n;j++, cnt++)//从第三的基数开始,
			cout << t[j];
		if (j == t.length()) {
			for (int k=0;k < n - cnt;k++)//继续小数点右移,低位补零
				cout << '0';

		}
		else {
			cout << '.';    //小数点没有移出前面基数范围
			for (int k = j;k < t.length();k++)//加小数点,接着输出基数
				cout << t[k];
		}
	}
	system("pause");
    return 0;
}
发布了32 篇原创文章 · 获赞 1 · 访问量 5401

猜你喜欢

转载自blog.csdn.net/Li060703/article/details/88804280