第一种: 不需要反转处理字符数组的两种方法:
#include <stdio.h>
*判断闰年*/
main()
{
int year;
printf("Please enter the year:");
scanf("%d",&year);
if((year%4==0)&&(year%100!=0))
printf("%d is a leaf year!\n",year);
else if(year%400==0)
printf("%d is a leaf year!\n",year);
else
printf("%d is not a leaf year!\n",year);
}
#include <stdio.h>
#include <math.h>
main()
{
char num[] = "14028";
int a = atoi(num);
printf("%d\n",a);
}
*atoi: convert a string to an integer*/
//Method1: Don't need to reverse the array in the process
int atoi(char str[])
{
int result=0, i, n = 0;
//判断字符串结尾获取字符数组的长度
while(str[n] != '\0')
++n;
for(i=0;i<=n;++i)
{
//refer the lib method, pow(m,n)
result += (str[i]-'0')*pow(10,n-1-i);
}
return result;
}
/*条件语句str[i]>='0'&&str[i]<='9'的好处是:
1,因为字符串的最后一个字符'\0',它的ASCII值是0,本身就不在上述条件中'0'<x<'9'中,省去了判断字符串结尾获取字符数组的长度的语句。
2,result = result*10 + (str[i]-'0')隐含了每次运算进位10
*/
int atoi(char str[])
{
int i, result=0;
for(i=0;str[i]>='0'&&str[i]<='9';++i)
{
result = result*10 + (str[i]-'0');
}
return result;
}
第二种方法:
更为通用,利用标准库ctype.h进行字符判断
#include <stdio.h>
#include <math.h>
/*ctype.h是字符类别测试函数库*/
#include <ctype.h>
int atoi(char);
int main()
{
int result = 0;
char s[100];
printf("Enter the number: \n");
scanf("%s",s);
result = atoi(s);
printf("The result is %d\n",result);
}
int atoi(char s[])
{
int i, n, sign;
/*若有空白符,跳过*/
for(i=0; isspace(s[i]); i++)
;
/*定义一个符号变量,若遇到'-',该值为-1*/
sign = (s[i] == '-')? -1 : 1;
/*若有符号,则读取符号*/
if(s[i]=='+'||s[i]=='-')
i++;
for(n=0; isdigit(s[i]); i++)
n = 10*n + (s[i]-'0');
return sign * n;
}