- 實例要求:
atoi函數
的功能是把字符串轉成整型數值并輸出;- 把
字符串"123456"
轉換成數值123456
,并返回數值; - 函數名:
int myatoi(char *str);
-
實例分析:
-
1.自定義的封裝函數類型是整型,所以
返回值也是整型
,因此,在atoi函數
中需要使用return關鍵字
返回一個整型變量; -
2.可以使用for循環或while循環,對從main函數傳入的字符串進行遍歷,直到
字符串的'\0'
結束; -
3.
'0'
的ASCII值
是48
,那么'1'到'6'
的ASCII值的范圍
是49到54
; -
4.利用公式
key = key * 10 + *str - '0'
,把字符型轉換成整型,結束循環后輸出; -
測試代碼:
#include<stdio.h>int myatoi(char *str){int key = 0;while(*str!= '\0'){key = key*10 + *str - '0';str++;}return key;}int main(int argc, const char *argv[])
{char s[10] = "123456";int tmp = myatoi(s);printf("%d\n",tmp);return 0;
}
- 運行結果:
123456