首页 > 解决方案 > 使用 char 类型将十进制转换为字符串和字符串转换为十进制

问题描述

我的代码没有给我确切的值。有人可以告诉我有什么问题吗?一些值给了我正确的答案,但是尝试78,7980你就会知道。

如果你能以某种方式纠正它,那就太好了。

//hi // Example program
#include <iostream>
#include <string>
using namespace std;

int stringToDecimal(string X)
{
    int digit = 0;
    //I believe there is some fault here.

    for (int i = 0;i < (X.length() -1); i++)
    {
        char c = X[i] + 48;     
        digit = (c + (10 ^ i) )+ digit;
    }
    return digit;
}

int countDigit(int n)
{
    int count = 0;
    while (n != 0) {
        n = n / 10;
        ++count;
    }
    return count;
}

//I believe there is some fault here too
string DecimalToString(int x)
{
    string a= "";
    for (int i =0 ; i < countDigit(x); i++)
    {
        char digit = (x / (10 ^  i)) % 10;
        char c = digit + 48;
        a = a +c;
    }
    cout << endl; 
    return a;
}

int main()
{
    cout << "enter an integer" << endl;
    int a;
    cin >> a;
    cout << DecimalToString(a) << endl;
    cout << stringToDecimal(DecimalToString(a));
    system("pause");
    return 0;
}

标签: c++string

解决方案


恕我直言,算法如下(也适用于二进制):

Set value to zero.  
For each digit (left to right):  
    multiply value by base (a.k.a. 10).
    add in digit value
    end-for

给定一个字符串作为输入,代码可能看起来像这样:

std::string number_as_text = "85";
int value = 0;
const size_t number_text_length = number_as_text.length();
for (unsigned int i = 0; i < number_text_length; ++i)
{
  value = value * 10; // Shift left by one digit.
  value += number_as_text[i] - '0';
}

该算法不需要除法,这让处理器非常高兴。
没有浮点转换。


推荐阅读