makefile
.SUFFIXES: .c .o CC=gcc SRCS=test.c OBJS=$(SRCS:.c=.o) EXEC=test all: $(OBJS) $(CC) -o $(EXEC) $(OBJS) @echo '-------------ok--------------' .c.o: $(CC) -Wall -g -o $@ -c $< clean: rm -f $(OBJS) rm -f core*
myitoa
#include <stdio.h> #include <string.h> void resver(char *s)//反转字符串 { int len = strlen(s); //printf("len=%d\n",len); int i = 0; char tmp = 0; for (; i<len/2; i++) { tmp = s[i]; s[i] = s[len-1-i]; s[len-1-i] = tmp; } } const char *myitoa(int n) { static char buf[100];//必须为static,或者是全局变量 memset(buf, 0, sizeof(buf)); int FlagF = 0; //1-f, 0-z int i = 0; if (n < 0) { FlagF = 1; n = 0 - n; } while (n) { buf[i++] = n % 10 + '0'; n = n / 10; } if (FlagF == 1) { buf[i++] = '-'; } buf[i] = '\0'; printf("before buf:%s\n", buf); resver(buf); printf("after buf:%s\n", buf); return buf; } int main() { printf("%s\n", myitoa(123)); printf("%s\n", myitoa(-123)); return 0; }
myatoi
#include <stdio.h> int mystrlen(const char *s) { int i = 0; while (*s++) { i++; } return i; } int power10(int n) { if (n == 0) { return 1; } int val = 1; int i = 0; for (; i < n; i++) { val = val * 10; } return val; } int char2i(char c) { if ((c >= '0') || (c <= '9')) { return (c - '0'); } else { return 0; } } int myatoi(const char *str) { int FlagF = 0; //1-f, 0-z const char *p = str; int i = 0; int value = 0; if (str[0] == '-') { FlagF = 1; // p = ++str; } int len = mystrlen(p); int lentmp = len; for (; i < len; i++) { value += char2i(p[i]) * power10(lentmp - 1); lentmp--; } if (FlagF == 1) { return (0 - value); } else { return value; } } int main() { const char *s = "-123"; printf("%d\n", myatoi(s)); return 0; }