生活随笔
收集整理的這篇文章主要介紹了
算法题:科学计数法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
科學計數法是科學家用來表示很大或很小的數字的一種方便的方法,其滿足正則表達式[+-][1-9]”.”[0-9]+E[+-][0-9]+,即數字的整數部分
只有1位,小數部分至少有1位,該數字及其指數部分的正負號即使對正數也必定明確給出。
現以科學計數法的格式給出實數A,請編寫程序按普通數字表示法輸出A,并保證所有有效位都被保留。
輸入描述:
每個輸入包含1個測試用例,即一個以科學計數法表示的實數A。該數字的存儲長度不超過9999字節,且其指數的絕對值不超過9999。
輸出描述:
對每個測試用例,在一行中按普通數字表示法輸出A,并保證所有有效位都被保留,包括末尾的0。
輸入例子:
+1.23400E-03
輸出例子:
0.00123400
#include <iostream>
#include <string.h>
using namespace std;
int GetNum(
char *str)
{
char *p = str;
int count =
0;
while (*p ==
'0')p++;
while (*p != NULL){count = count *
10 + *p -
'0';p++;}
return count;
}
void SetStr(
char *&str,
int n)
{
string s;
char *s1 = strtok(str,
".");
int len1 =
0;
if (s1[
0] ==
'+' || s1[
0] ==
'-'){
if (s1[
0] ==
'-'){s +=
'-';s1++;}
if (s1[
0] ==
'+')s1++;len1 =
strlen(s1);}
else len1 =
strlen(s1);
if (n < len1){
int i = len1 - n;
while (i--){s += *s1;s1++;}s +=
'.';s += s1;}
else{s +=
"0.";
int i = n - len1;
while (i--){s +=
'0';}s += s1;}s1 = strtok(NULL,
"\0");
if (s1!=NULL)s += s1;
cout << s.c_str() << endl;
}
void SetTtr(
char *str,
int n)
{
string s;
if (str[
0] ==
'+' || str[
0] ==
'-'){
if (str[
0] ==
'-'){s +=
'-';}str++;}
char *s1 = strtok(str,
".");
if (
strlen(s1) == n){s += s1;
while (n--){s +=
'0';}}
else{s += s1;s1 = strtok(NULL,
"\0");
while (*s1!=
'\0' && n--){s += *s1;s1++;}
if (*s1 ==
'\0'){
while (n--){s +=
'0';}}
else{s +=
'.';s += s1;}}
cout << s.c_str() << endl;
}
int main()
{
char inputStr[
10000];
cin >> inputStr;
char *s1 = strtok(inputStr,
"E");
char *saveStr1 =
new char[
strlen(s1)+
1];
strcpy(saveStr1,s1);s1 = strtok(NULL,
"\n");
char *saveStr2 =
new char[
strlen(s1) +
1];
strcpy(saveStr2,s1);
char ch = saveStr2[
0];
int N;
char *p = NULL;
switch (ch){
case '+':p = saveStr2;N = GetNum(++p);SetTtr(saveStr1, N);
break;
case '-':p = saveStr2;N = GetNum(++p);SetStr(saveStr1,N);
break;
default:
break;}
return 0;
}
總結
以上是生活随笔為你收集整理的算法题:科学计数法的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。