c++ - 使用 char 类型将十进制转换为字符串和字符串转换为十进制
问题描述
我的代码没有给我确切的值。有人可以告诉我有什么问题吗?一些值给了我正确的答案,但是尝试78
,79
等80
你就会知道。
如果你能以某种方式纠正它,那就太好了。
//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;
}
解决方案
恕我直言,算法如下(也适用于二进制):
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';
}
该算法不需要除法,这让处理器非常高兴。
没有浮点转换。
推荐阅读
- pandas - Pandas,将所有数据框转换为唯一的分类值
- react-native - 标头在本机反应中不可见
- arrays - Mongodb嵌套数组匹配
- scala - 如何从 http 响应中保存标头
- bash - 我目前在两台机器上运行 cron 脚本来执行任务 - 我可以将它们组合成一个使用两台服务器的脚本吗?
- c++ - 如何在派生构造函数中初始化从基类继承的向量
- excel - 使用 While 循环获取特定列中的行句柄
- c# - 为什么这个 Base36 随机字符串不使用 RandomNumberGenerator 随机分布字符
- java - Jenkins - 带有动态 html 报告文件的电子邮件附件
- python - 如果有其他没有标签的盒子,如何抓取某些标签