Cool Coder
170870024
全部博文(54)
2011年(1)
2009年(30)
2008年(23)
q3945496
liubenyu
18975172
47001252
ans4
ymcheng
翊耙耙
xjhunter
yanleide
分类: C/C++
2008-11-02 23:40:15
#include<stdio.h>int atoi(const char *str){ int value=0; bool b_plus=true; //判断符号 switch(*str) //过滤符号 { case '+': str++; break; case '-': b_plus=false; str++; break; default: break; } while('\0' != *str) { value = (value*10)+(*str-'0'); str++; } if(!b_plus) value=-value; return value;}void main(){ char str[]="-999"; int value=atoi(str); printf("The result is:%d\n",value);}
(2)itoa的实现:
#include<stdio.h>void itoa(int value, char *str){ if (value < 0) //如果是负数,则str[0]='-',并把value取反(变成正整数) { str[0] = '-'; value = 0-value; } int i,j; for(i=1; value > 0; i++,value/=10) //从value[1]开始存放value的数字字符,不过是逆序,等下再反序过来 str[i] = value%10+'0'; //将数字加上0的ASCII值(即'0')就得到该数字的ASCII值 for(j=i-1,i=1; j-i>=1; j--,i++) //将数字字符反序存放 { str[i] = str[i]^str[j]; str[j] = str[i]^str[j]; str[i] = str[i]^str[j]; } if(str[0] != '-') //如果不是负数,则需要把数字字符下标左移一位,即减1 { for(i=0; str[i+1]!='\0'; i++) str[i] = str[i+1]; str[i] = '\0'; }}void main(){ int value = -1212345; char str[10] = {'\0'}; //记得把str全填充为'\0' itoa(value, str); printf("The result is:%s\n", str);}
上一篇:C/C++笔试题(1)
下一篇:八皇后问题(递归&非递归)
登录 注册