c++:将八进制转换成十进制
时间: 2024-09-26 15:09:18 浏览: 37
在C++中,你可以通过直接将八进制数解析为整数来将其转换为十进制。这通常使用内置的`stoi`函数或者手动逐位相加的方式来实现。以下是两种方法的例子:
**方法一:使用`stoi`函数**
```cpp
#include <iostream>
#include <string>
int octal_to_decimal(const std::string& octal_number) {
return std::stoi(octal_number, nullptr, 8);
}
int main() {
std::string octal = "0123";
int decimal = octal_to_decimal(octal);
std::cout << "Octal " << octal << " is equal to Decimal " << decimal << std::endl;
return 0;
}
```
**方法二:手动转换**
```cpp
int octal_to_decimal(int octal_num) {
int decimal = 0;
for (int i = 0; i < std::strlen(octal_num); ++i) {
if (octal_num[i] >= '0' && octal_num[i] <= '7') { // 只考虑有效八进制字符
decimal *= 8;
decimal += octal_num[i] - '0';
}
}
return decimal;
}
int main() {
std::string octal = "0123";
int decimal = octal_to_decimal(stoi(octal));
std::cout << "Octal " << octal << " is equal to Decimal " << decimal << std::endl;
return 0;
}
```
阅读全文