[Algorithms, C] long2char: 自己用C写来玩玩的整形转化为字符串函数 (递归和迭代两种实现): void long2char(long from, char *to, int n);
2011-06-19 23:06
489 查看
void long2char(long from, char *to, int n); // 递归和迭代两种实现
/* long2char.c * Author: dooit.lee@gmail.com * Date: Sun Jun 19, 2011 */ #include <stdio.h> #include <stdlib.h> /* * from: int, to: char*, `n' means n digits of `from' with to[n + 2] */ void long2char(long from, char *to, int n) { int digit; if (from < 0) { *to = '-'; to++; from = -1 * from; } #if 0 // Recursion digit = from % 10; if ((from /= 10) != 0) { long2char(from, to, n - 1); } to[n - 1] = '0' + (digit - 0); #else // Iteration do { digit = from % 10; to[--n] = '0' + (digit - 0); } while ((from /= 10) != 0); #endif } int main(int argc, char *argv[]) { long from; int n, i; char *to, *endptr; if (argc != 2 || !atoi(argv[1])) { bad: fprintf(stderr, "Usage: %s <integer-number>/n", argv[0]); exit(1); } else { from = strtol(argv[1], &endptr, 10); if (argv[1] == endptr) goto bad; n = 1; i = from; while ((i /= 10) != 0) ++n; // include a '-' and '/0' charachter to = calloc(n + 2, sizeof(char)); if (to != NULL) { long2char(from, to, n); printf("%s/n", to); free(to); } else { fprintf(stderr, "%s: Cannot allocate memory/n", argv[0]); } } return 0; }
相关文章推荐
- C语言自己实现的 整形转换成字符串函数itoa(int Number,char* Str)
- 编写一个程序以确定分别由signed及unsigned限定的char、short、int及long类型变量的取值范围。采用打印标准头文件中的相应值以及直接计算两种方式实现
- 练习2-1 编写一个程序一确定分别由signed及unsigned限定的char,short,int及long类型变量的取值范围。采用打印标准头文件中的相应值以及直接计算两种方式实现。通过直接计算来确定浮点类型的取值范围是一项难度很大的任务。
- error: cast from ‘char*’ to ‘int’ loses precision
- x86_64 xercexc: error: cast from 'const void*' to 'long int' loses precision [-fpermissive]
- 二分搜索算法(折半查找)原理以及递归(recuition),迭代(iteration)的两种实现源代码
- Incompatible integer to pointer conversion assigning to 'NSInteger *' (aka 'long *') from 'int'
- 递归 / 迭代两种方法实现查找指定目录下所有文件
- C语言实现斐波那契数列的两种方法(递归和迭代)
- LoadCursorA' : cannot convert parameter 2 from 'const int' to 'const char *
- LeetCode 206. Reverse Linked List(迭代和递归两种实现)
- 斐波那契数列的两种实现方式(递归(大于O(n方))和迭代(O(n))----网易笔试2013录
- error: cast from ‘char*’ to ‘int’ loses precision
- 斐波那契数列的两种实现方式(递归(大于O(n方))和迭代(O(n))----网易笔试2013录
- Java 对byte,short,char,int,long 运算时自动类型转化情况说明
- int ascii_to_integer(char *str)函数 将一串数字字符转化成对应的整形数字
- 迭代与递归(及异同点的简单分析)以及Fibonacci数列的两种实现
- java对byte,short,char,int,long运算时自动类型转化情况说明
- error C2664: 'LONG CTabCtrl::InsertItem(int,TCITEMW *)' : cannot convert parameter 2 from 'char *' t
- Java中char 转化为int 的两种方法