//整形转成字符串函数实现 //题目不难,重点考察面试者对问题考虑的全面程度 #include <iostream> using namespace std; void itoa_mf(int num,char str[]) { int sign = num; int i = 0; int j = 0; char temp[100]; //如果是负数就去掉符号,将-1234转成1234 if(sign < 0) { num = -num; } //转成字符串,1234转成"4321" do { temp[i] = num % 10 + '0'; num /= 10; i++; }while(num > 0); //如果是负数的话,加个符号在末尾,如:"4321-" if(sign < 0) { temp[i++] = '-'; } temp[i] = '\0'; i--; //将temp数组中逆序输入到str数组中 //将"4321-" ====> "-1234" while(i >= 0) { str[j] = temp[i]; j++; i--; } //字符串结束标识 str[j] = '\0'; } //测试用例 void main() { int a = 0; char s[100]; itoa_mf(a,s); cout << s << endl; }