赞
踩
/* 编写函数,实现与库函数atoi、atol、atof相同的功能 */ #include <stdio.h> int strtoi(const char *nptr) { int ans = 0; int sign = 1; while (*nptr == ' ') nptr++; if (*nptr == '+') { nptr++; } else if (*nptr == '-') { sign = -1; nptr++; } while (*nptr >= '0' && *nptr <= '9') { ans *= 10; ans += sign * (*nptr++ - '0'); } return ans; } long strtol(const char *nptr) { long ans = 0; int sign = 1; while (*nptr == ' ') nptr++; if (*nptr == '+') { nptr++; } else if (*nptr == '-') { sign = -1; nptr++; } while (*nptr >= '0' && *nptr <= '9') { ans *= 10; ans += sign * (*nptr++ - '0'); } return ans; } double strtof(const char *nptr) { int sig_base = 1, index = 0, sig_index = 1; double ans = 0.0, digit = 1.0; while (*nptr == ' ') nptr++; if (*nptr == '+') { nptr++; } else if (*nptr == '-') { sig_base = -1; nptr++; } while (*nptr >= '0' && *nptr <= '9') { ans *= 10; ans += sig_base * (*nptr++ - '0'); } if (*nptr == '.') { nptr++; while (*nptr >= '0' && *nptr <= '9') { digit *= 10; ans += sig_base * (*nptr++ - '0') / digit; } } if (*nptr == 'e' || *nptr == 'E') { nptr++; if (*nptr == '+') { nptr++; } else if (*nptr == '-') { sig_index = -1; nptr++; } while (*nptr >= '0' && *nptr <= '9') { index *= 10; index += sig_index * (*nptr++ - '0'); } while (index != 0) { ans *= index > 0 ? 10 : 0.1; index > 0 ? index-- : index++; } } return ans; } int main() { char str[128]; enum func {STRTOI, STRTOL, STRTOF} selected; printf("0>>>转换为int型\n1>>>转换为long型\n2>>>转换为double型\n请输入数字选择相应的功能:"); scanf("%d", &selected); printf("请输入要转换的字符串:"); scanf("%s", str); if (selected == STRTOI) printf("%d", strtoi(str)); else if (selected == STRTOL) printf("%ld", strtol(str)); else printf("%f", strtof(str)); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。