c++ 将整数从一个基数改为另一个基数时输出的随机字符

6vl6ewon  于 2023-05-02  发布在  其他
关注(0)|答案(1)|浏览(104)

我正在做一个赋值运算,我应该把一个整数从一个基数转换到另一个基数。程序要求输入当前基数、当前基数中的数字以及要转换的新基数。
我将输入这些值,例如:

Please enter the number's base:10
Please enter the number:4136490862
Please enter the new base: 10

输出将是:

4136490862 base 10 is -2-1-4-7-4-8-3-6-4-8 base 10

正确的输出是:

4136490862 base 10 is 4136490862 base 10

还有其他测试用例,这只是其中一个不起作用的。
我已经纠结了好几天了。有人知道我错在哪里吗?
代码如下:

#include <iostream>
#include <string>
#include <istream>
#include <cmath>
 
int main(void){
 
    std::string num;
    int currentBase;
    int newBase;
    int lastDigit;
    int i = 0;
    int sum = 0;
    int remainder;
    std::string new_number = "";
 
 
    //Get the current base from the user
    std::cout <<"Please enter the number's base: ";
    std::cin >> currentBase;
 
    //enter the number of that base
    std::cout <<"Please enter the number: ";
    std::cin >> num;
 
    //enter the new base you want to convert it to
    std::cout <<"Please enter the new base: ";
    std::cin >> newBase;
 
    //just a check to see if the base is valid cuz valid bases are only from 2-36
    if ((currentBase < 2) || (currentBase > 36) || (newBase < 2) || (newBase > 36)){
        std::cout << "One or more of the bases that you entered are not valid!" << std::endl;
        return 1;
    }
 
    //Convert the input string to base 10
    //iterate through the number from least significant to most significant digit
    for(int j = num.size() - 1; j >= 0; j--) {
        char c = num[j];
        if (isdigit(c)) {
            lastDigit = c - '0';
        } else if (isupper(c)) {
            lastDigit = c - 'A' + 10;
        } else if (islower(c)) {
            lastDigit = c - 'a' + 10;
        }
        sum += lastDigit * pow(currentBase, i);
        i++;
    }
 
    //Convert the base 10 number to the desired base
    while (sum != 0) {
        remainder = sum % newBase;
        if (remainder < 10) {
            new_number = std::to_string(remainder) + new_number;
        } else {
            new_number = char(remainder - 10 + 'A') + new_number;
        }
        sum /= newBase;
    }
 
    //print everything out
    std::cout << num << " base " << currentBase << " is " << new_number << " base " << newBase << std::endl;
 
    return 0;
};
vof42yt1

vof42yt11#

4136490862不能存储在int中。我假设您的意图是应该使用unsigned int,但更简单和更安全的解决方案是使用long long

相关问题