C中的倒数功能 [英] Reverse number function in C

查看:66
本文介绍了C中的倒数功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,如果我输入092,它不会返回290,而是返回29,这不是我想要的.有什么建议吗?

So if I input say 092, it does not return 290, instead returns 29 which is not what I want it to do. Any advice?

int reverseNumber(int number){
    int ans = 0;
    while(number > 0) {
        int rightDigit;
        rightDigit = number % 10;
        ans =ans *10 + rightDigit;
        number = number / 10;
    }
    return ans; 
}

推荐答案

这是因为 029 29 十进制 1 没有区别.为此,您需要将输入作为字符串,然后反转字符.之后,您可以将结果字符串转换为数字.

It is because 029 is no different from 29 decimal1. For this to work you need to take the input as a string instead, and invert the characters. After that you can convert the resulting string to a number.

1 前导0表示它是一个八进制数字,但是在这种特殊情况下,它的9并非八进制数字.根据您从数字转换为字符串的方式,可能需要考虑这一点.但是,如果您只是对其进行 scanf(),则可以肯定使用十进制.

1A leading 0 means it's an octal number, but in this particular case it has a 9 which is not an octal digit. Depending on how you convert from numbers to strings, this can be something to consider. But if you are just scanf()ing it, then it will be decimal for sure.

这篇关于C中的倒数功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆