c++其他进制转十进制
时间: 2023-11-18 09:05:33 浏览: 70
c++可以使用以下方法将其他进制转换为十进制:
1.二进制转十进制:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
int main() {
long long binary, decimal = 0;
int i = 0, remainder;
cout << "Enter a binary number: ";
cin >> binary;
while (binary != 0) {
remainder = binary % 10;
binary /= 10;
decimal += remainder * pow(2, i);
++i;
}
cout << "Decimal number is: " << decimal << endl;
return 0;
}
```
2.八进制转十进制:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int octal, decimal = 0, i = 0;
cout << "Enter an octal number: ";
cin >> octal;
while (octal != 0) {
decimal += (octal % 10) * pow(8, i);
++i;
octal /= 10;
}
cout << "Decimal number is: " << decimal << endl;
return 0;
}
```
3.十六进制转十进制:
```cpp
#include <iostream>
#include <cmath>
using namespace std;
int main() {
string hexadecimal;
long long decimal = 0;
int i = 0, val;
cout << "Enter a hexadecimal number: ";
cin >> hexadecimal;
for (auto it = hexadecimal.rbegin(); it != hexadecimal.rend(); ++it) {
if (*it >= '0' && *it <= '9') {
val = *it - '0';
} else if (*it >= 'a' && *it <= 'f') {
val = *it - 'a' + 10;
} else if (*it >= 'A' && *it <= 'F') {
val = *it - 'A' + 10;
} else {
cout << "Invalid hexadecimal number!" << endl;
return 0;
}
decimal += val * pow(16, i);
++i;
}
cout << "Decimal number is: " << decimal << endl;
return 0;
}
```
以上是三种进制转换为十进制的方法,可以根据需要进行选择。