我有一个很奇怪的问题。 我正在做的是尝试将字符串中的 8 位二进制数转换为十进制数(也是字符串) 在代码的末尾,我计算出二进制字符串和十进制字符串,但是当我运行时,我只成功看到了二进制字符串,但看不到十进制字符串...
这是我的代码:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
void bintodec(string bin);
int main()
{
string bin="";
bintodec(bin);
return 0;
}
void bintodec(string bin)
{
int temp;
int temp_a;
int temp_b;
string dec;
cout << "Enter the binary number: ";
cin >> bin;
temp = 128*(bin[0]-48) + 64*(bin[1]-48) + 32*(bin[2]-48) + 16*(bin[3]-48) + 8*(bin[4]-48) + 4*(bin[5]-48) + 2*(bin[6]-48) + (bin[7]-48);
temp_a = temp%10;
temp = (temp - temp_a) / 10;
temp_b = temp%10;
temp = (temp - temp_b) / 10;
dec[2]=temp_a+48;
dec[1]=temp_b+48;
dec[0]=temp+48;
dec[3]='\0';
cout << endl << bin << " in decimal is: " << dec << endl;
}
这是运行结果:
Enter the binary number: 10101010
10101010 in decimal is:
“is”后面应该是我的十进制数;然而什么也没有。我尝试分别计算 dec[0] dec[1] 和 dec[2] 并且它有效,但是当我计算整个 dec 时,我每次都失败......
谁能告诉我我的问题出在哪里?我认为我的代码有问题,但我可以弄清楚......
最佳答案
dec
的大小为零。但是您访问位置 0 到 3 的元素。
例如,您可以使用
dec
string dec(4, ' '); // fill constructor, creates a string consisting of 4 spaces
而不是
string dec;
.
关于C++ 当我成功计算出另一个字符串时,我无法计算出一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18537630/