/************************************ 将整数转换为相应的一个字符数组。 分析:从个位提取数字,组合字符 符号位的处理 12345=>"12345" ************************************/ #include <stdio.h> int IntToStr(int num, char *str) { if (str == NULL) { return -1; } int len = 0; int count = 0; int temp = num; int flag = 0; while (num) //计算整数的位数 { num /= 10; len++; } count = len; if (temp < 0) { temp *= -1; flag = 1; //负数先转换为正数,标记为1 } while (temp) { str[--len] = temp % 10 + '0'; //将整数的各位数转换为字符 temp /= 10; } str[count] = '\0'; //加上结束标志'\0' if (flag == 1) { len = count; while (len >= 0) //负数处理,字符串整体后移1位,第一位放上'-' { str[len + 1] = str[len]; len--; } str[0] = '-'; } return 0; }
转载请注明原文地址: https://www.6miu.com/read-36686.html