1. 程式人生 > >.編寫一個函式,將一個數字字串轉換成該字串對應的數字

.編寫一個函式,將一個數字字串轉換成該字串對應的數字

 /*
編寫一個函式,將一個數字字串轉換成該字串對應的數字(包括正整數、負整數)
例如:“12“  	返回12
	 “-123“ 返回-123
函式原型:int my_atof(char *str){}
*/
#include<stdio.h>
#define MAXSIZE 100
int my_atof(char *str)
{
	int a = 0;       //整數
	int state;       //記錄符號
	if(*str == '-')
	{
		state = -1;
		while(*(++str) != '\0')    //注意!!!!首位'-'不能加入到a中
		{
			a = a*10+(*str - '0');
		}
	}
	else
	{
		state = 1;
		while(*str != '\0')   
		{
			a = a*10+(*str - '0');
			str++;
		}
	}

	return state*a;
}
int main()
{
	char a[MAXSIZE]="123344";
	char b[MAXSIZE]="-123344";
	printf("%d\n",my_atof(a));  
	printf("%d\n",my_atof(b));
	return 0;
}