練習 字串轉數字

2021-06-23 01:13:02 字數 650 閱讀 9613

上些時間到tx面試,被問到如何寫乙個字串轉為數字雖然,這是乙個自己覺得也很簡單的題目,但自己寫程式比較少,手上功夫生了,感到很慚愧今天有空,自己被了乙個,大家看看有沒有什麼寫的不好,指出來吧。

#include #include //by ljg 2014-8-1
//使用遞迴的方法把字串轉為數字

int atoi2(const char *str,int a,int *err)

else

int b = a *10 +(*str - '0');

printf("b is %d\n",b);

if(b < a)

return atoi2(str+1,b,err); }}

//先把負號找出來,再把字串轉為數字

int atoi(const char *str)

int err = 0;

int a = atoi2(str,0,&err);

if(err)a = 0;

else if(isnegative)

printf("string is %s, a is %d\n",str,a);

return a;

}int main()

字串 字串轉數字

題目 將乙個字串轉換成數字。例如 123 123,71.02 71.02.方法一,直接呼叫庫函式atoi const char 和atof const char stoi string str include include int main 輸出結果 num int 435 num double ...

字串轉數字

注意進製,注意小數,負數,指數。小數跟指數比較繁瑣。應該對字串做限制,字串只是整數字串。否則,以下幾種情況都是會報錯 1.0x011.011,0b011.011都是錯誤的。2.0100.011實際上是十進位制的100.01。3.指數表示造成邏輯更多了。鑑於以上幾個情況考慮,為簡化,整數字串轉數字。草...

字串轉數字

看了劍指offer上面的第一道題,字串轉數字,就去查了下,有多種方法。比如可以直接用函式atoi 下面是我的 include include include include includeusing namespace std int main string a 100 int num 0 if a...