PAT 1024 科學(xué)計(jì)數(shù)法 (20 分)

#include <iostream>
#include<cstring>
#include<cstdio>
using namespace std;

int main() {
  char str[10000];
  scanf("%s",str);
  int len=strlen(str);
  if(str[0]=='-') printf("-");
  int pos=0;//存放E的 位置 
  while(str[pos]!='E') pos++;
  //指數(shù) 
  int exp=0;
  for(int i=pos+2;i<len;i++)
    exp=exp*10+(str[i]-'0');
  if(exp==0){//指數(shù)為零 
    for(int i=1;i<pos;i++) printf("%c",str[i]);
  }  
  if(str[pos+1]=='-')//指數(shù)為負(fù) 
  {
    printf("0.");
    for(int i=0;i<exp-1;i++) printf("0");
    printf("%c",str[1]);
    for(int i=3;i<pos;i++) printf("%c",str[i]);
  }
  else//指數(shù)為正 
  {
    for(int i=1;i<pos;i++){//輸出移動(dòng)后的數(shù) 
      if(str[i]=='.') continue;//跳過原小數(shù)點(diǎn) 
      printf("%c",str[i]);
      if(i==exp+2&&pos-3!=exp) printf(".");
    }
    for(int i=0;i<exp-(pos-3);i++) printf("0");//輸出多余的 0
  }
    return 0;
}

方法2

#include <iostream>
#include <string>
#include<string.h>
using namespace std;
int main(){
    string a, res;
    cin >> a;
    int k = 0;
    char ch = a[0];
    int flag = 0;
    while (a[k] != 'E') {            //記錄有效數(shù)字
        if (strchr("+0.-", a[k]) == NULL)
            flag = 1;
        if (isdigit(a[k]) && flag) 
            res += a[k];
        k++;
    }
    int l = a.substr(a.find('.'), a.find('E')).length() - 3;   //記錄小數(shù)位數(shù)
    int c = stoi(a.substr(a.find('E') + 1, a.length()));        //記錄指數(shù)
    k = c - l;
    if (k < 0) {
        while (res.length() < abs(k))     //小數(shù)位補(bǔ)0
            res = '0' + res;
        res.insert(res.end() + k, '.');        //插入小數(shù)點(diǎn)
        if (res[0] == '.')                //若是小數(shù)之前還需補(bǔ)0
            res = '0' + res;
    }
    else {
        while (k--)            //整數(shù)末尾補(bǔ)0
            res += '0';
    }
    if (ch == '-')            //如果是負(fù)數(shù)還需補(bǔ)負(fù)號(hào),切記正數(shù)不用
        res = ch + res;
    cout << res;
    return 0;
}

GitHub

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容