c++ 使用运算符反转cpp中整数的代码

hec6srdp  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(115)

该代码是为扭转输入十进制无论是负或正.如果十进制的值超过作为最大大小的整数在32位系统然后返回0.为什么我的代码是不工作...帮助我找到的bug .我已经附上的代码.

#include<iostream>
#include<stdlib.h>
#include<math.h>
using namespace std;
float reverseint(int x)
{
    int digit[10];
    int i = 0;
    float revnum = 0;
//store digits of number x
    while (x != 0)
    {
        digit[i] = x % 10;
        x = x / 10;
        i++;
    }
    i--;
//reversing number x
    while (i >= 0)
    {
        int j = 0;
        revnum = (digit[i] * pow(10, j)) + revnum;
        j++;
        i--;
    }
    return revnum;
}
int main()
{
    int n;
    cin >> n;
    if (n < 0)
    {
        if (n < -pow(2, 31))
            cout << 0 << endl;
        cout << -reverseint(-n);
    }
    if (n > 0)
    {
        if (n > (pow(2, 31) - 1))
            cout << 0 << endl;
        cout << (reverseint(n)) << endl;
    }
    return 0;
}
pw9qyyiw

pw9qyyiw1#

您正在reverseint函数的每个while循环中初始化j变量。

float reverseint(int x)
{
    int digit[10];
    int i = 0;
    float revnum = 0;
//store digits of number x
    while (x != 0)
    {
        digit[i] = x % 10;
        x = x / 10;
        i++;
    }
    i--;
//reversing number x
    int j = 0; /// Correct place.
    while (i >= 0)
    {
        //int j = 0; /// Wrong. j will be always 0 on every loop. revnum  will be sum of digits on variable x.
        revnum = (digit[i] * pow(10, j)) + revnum;
        j++;
        i--;
    }
    return revnum;
}

相关问题