// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
char *itostr(int n, char *string)
{
static int i = 0;
if (n < 0) //当输入为负数时需要加上‘-’
{
n = -n;
i++;
string[0] = '-';
}
if (n / 10 == 0) //n此时只剩一位数即为最后一位,需要在末尾加上‘\0’
{
string[i] = n + '0';
string[i + 1] = '\0';
}
else
{
itostr(n / 10, string);//利用整除取数进行递归调用
i++;
string[i] = (n % 10) + '0';//利用模10取余获取最右位数字并转换成字符
string[i + 1] = '\0';//末尾需要加上‘\0’表示结束
}
return string;
}
int _tmain(int argc, _TCHAR* argv[])
{
int n;
cout << "please input the number: " << endl;
cin >> n;
char str[100];
itostr(n, str);
cout << str << endl;
return 0;
}
,该函数将整数n转换为十进制表示的字符串。