首先关于函数atoi的重写,
atoi的功能是字符串能够转换为整数保存,仅仅针对于整数,浮点数以后会有写:
//实现一个函数int my_atoi(char s[]),可以将一个字符串转换为对应的整数。 #include <stdio.h> #include <ctype.h> int main() { char st[50]; gets(st); printf("%d",atoi(st)); return 0; } int atoi(char s[]) { int i,n,sign; for(i = 0;isspace(s[i]);i++) { ; } 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; }
itoa,将整数转化为字符串进行保存。
//实现一个函数itoa(int n,char s[]),将整数n这个数字转换为对应的字符串,保存到s中。 #include <stdio.h> #include <string.h> void itoa(int n,char s[]); int main() { int n; char st[50]; scanf("%d",&n); itoa(n,st); printf("%s",st); } void itoa(int n,char s[]) { int i,j,sign; i = 0; if((sign =n) < 0) n = -n; do { s[i++] = n % 10 + ‘0‘; }while((n /=10) > 0); if(sign < 0 ) s[i++] = ‘-‘; s[i] = ‘\0‘; for(i=0,j=strlen(s)-1;i<j;i++,j--) { int c = 0; c=s[i]; s[i]=s[j]; s[j]=c; } }
itob,进制转换的函数重写:
//编写一个函数itob(int n,char s[], int b),将整数n转换为以b进制的数。保存到s中。 #include <stdio.h> #include <string.h> void itob(int n,char s[],int b); int main() { int n,b; char st[50]; scanf("%d %d",&n,&b); itob(n,st,b); printf("%s",st); return 0; } void itob(int n,char s[],int b) { int i = 0,j = 0; for(i = 0;n > 0;i++) { if(n % b < 10) { s[i] = n % b + ‘0‘; n = n / b; } else { s[i] = n % b + ‘W‘; n = n / b; } } s[i] = ‘\0‘; for(i=0,j=strlen(s)-1;i<j;i++,j--) { int c = 0; c=s[i]; s[i]=s[j]; s[j]=c; } }
最后是字符的统计:
//编写一个程序统计输入字符串中: //各个数字、空白字符、以及其他所有字符出现的次数。 #include <stdio.h> #include <ctype.h> int main() { int ch; int countOne = 0; int countTwo = 0; int countThree = 0; int countFour = 0; int countFive = 0; int countSix = 0; int countSeven = 0; int countAight = 0; int countNine = 0; int countSpace = 0; int other = 0; while((ch = getchar()) != EOF) { if(ch == ‘1‘) countOne++; else if(ch == ‘2‘) countTwo++; else if(ch == ‘3‘) countThree++; else if(ch == ‘4‘) countFour++; else if(ch == ‘5‘) countFive++; else if(ch == ‘6‘) countSix++; else if(ch == ‘7‘) countSeven++; else if(ch == ‘8‘) countAight++; else if(ch == ‘9‘) countNine++; else if(isspace(ch)) countSpace++; else other++; } printf(" 1 = %d 2 = %d\n 3 = %d 4 = %d\n 5 = %d 6 = %d\n 7 = %d 8 = %d\n 9 = %d space = %d\n other = %d",countOne,countTwo,countThree,countFour, countFive,countSix,countSeven,countAight,countNine,countSpace,other); return 0; }
本文出自 “剩蛋君” 博客,请务必保留此出处http://memory73.blog.51cto.com/10530560/1677629
原文地址:http://memory73.blog.51cto.com/10530560/1677629