[英]c++, a converter from x number system to decimal
I wrote this code it seemed to good but the output is always 0 what could be the problem? 我写的这段代码看起来不错,但是输出始终为0可能是什么问题? I m just writing a code to convert from x number system to decimal.
我只是在编写代码,以将x数制转换为十进制。
#include <string>
#include <iostream>
using namespace std;
int main() {
string str;
long szam = 0, Dec, num, Base = 1, x,i=1;
cout << "the number : ";
cin >> str;
cout << "The input number system:";
cin >> x;
while (str[i] == '\0')
{
if (str[i] = 'A') { num = 10;}
else if (str[i] = 'B') { num = 11; }
else if (str[i] = 'C') { num = 12; }
else if (str[i] = 'D') { num = 13; }
else if (str[i] = 'E') { num = 14; }
else if (str[i] = 'F') { num = 15; }
else { num = str[i] - '0'; }
Dec = Dec + num * Base;
Base = Base * x;
}
cout << szam << endl;
return 0;
} }
If x smaller than 10 its easy but i cant handle the 10+ system because of the letter use of numbers. 如果x小于10,这很容易,但是由于使用数字字母,我无法处理10+系统。
Your i
should start from 0, not from 1. i
应该从0开始,而不是从1开始。
Your i
should be incremented within your loop. 你
i
应该在你的循环内增加。 As it stands right now, i
is never incremented, so it always has the value of 1
, so you are only ever looking at str[1]
. 就目前而言,
i
从未增加过,因此它始终具有1
的值,因此您只看过str[1]
。
Your loop should continue while str[i] != '\\0'
, not while str[i] == '\\0'
. 您的循环应在
str[i] != '\\0'
,而不是在str[i] == '\\0'
。
You might want to consider handling the case of not only the letters ABCDEF
but also the letters abcdef
. 您可能要考虑处理字母
ABCDEF
以及字母abcdef
。
您应该使用std :: stol完全满足您的需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.