整数转为十进制字符串

本文介绍了一个使用递归方法实现的C++函数,该函数可以将整数转换为十进制表示的字符串。文章提供了完整的代码示例,包括处理负数和INT_MIN特殊情况的细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述:
编写递归函数char * itostr (int n,char * string),该函数将整数n转换为十进制表示的字符串。(提示:使用递归方法)

#include <iostream>
#include<limits.h>

#define N 100
int i = 0;
char *itostr(int n, char *string) {
    if (n == INT_MIN) {
        string[i] = '-';
        i++;
        n = -(n + 1);
        string[i] = (n % 10) + 49;
        n /= 10;
        i++;
    }
    if (n < 0&&n!=INT_MIN) {
        string[i] = '-';
        i++;
        n = -n;
        
    }
    string[i] = (n % 10) + 48;
        if (n /10 == 0 ){
            return string;      
        }
        else {
            i++;
            return itostr(n / 10, string);
        }
    
}
int main()
{
    int n;
    char str[N];
    std::cout << "请输入n(-2147483648~2147483647):" << std::endl;
    std::cin >> n;
    std::cout << "装换结果为:"  << std::endl;
    if (n < 0) {
        itostr(n, str);
        std::cout << str[0];
    for (int j = i;j > 0;j--)
        std::cout << str[j];
    }
    else {
        itostr(n, str);
        for (int j = i;j >= 0;j--)
            std::cout << str[j];
    }
    return 0;
     
}

运行截图:
1601604-20190414211651731-485213592.png
1601604-20190414211703275-1525065257.png
1601604-20190414211718389-1879577282.png

转载于:https://www.cnblogs.com/izzwhf/p/10707038.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值