C++ 中八进制到十进制转换程序
给定八进制数作为输入,任务是将给定的八进制数转换为十进制数。
计算机中的十进制数以 10 为基数表示,而八进制数以 8 为基数表示,从数字 0 到 7 开始,而十进制数可以是 0 到 9 之间的任何数字。
若要将八进制数转换为十进制数,请执行以下步骤
- 我们将从右到左通过余数提取数字,然后用从 0 开始并增加 1 直到(数字数)-1 的次幂乘以它
- 由于我们需要进行八进制到二进制的转换,因此指数的基数将为 8,因为八进制有 8 个基数。
- 将给定输入的数字与基数和次幂相乘,并存储结果
- 将所有乘积值相加以获得最终结果,最终结果将是十进制数。
下面是将八进制数转换为十进制数的示意图。

示例
Input-: 451 1 will be converted to a decimal number by -: 1 X 8^0 = 1 5 will be converted to a decimal number by -: 5 X 8^1 = 40 4 will be converted to a decimal number by -: 4 X 8^2 = 256 Output-: total = 0 + 40 + 256 = 10
算法
Start Step 1-> declare function to convert octal to decimal int convert(int num) set int temp = num set int val = 0 set int base = 1 Set int count = temp Loop While (count) Set int digit = count % 10 Set count = count / 10 Set val += digit * base Set base = base * 8 End return val step 2-> In main() set int num = 45 Call convert(num) Stop
示例
#include <iostream>
using namespace std;
//convert octal to decimal
int convert(int num) {
int temp = num;
int val = 0;
int base = 1;
int count = temp;
while (count) {
int digit = count % 10;
count = count / 10;
val += digit * base;
base = base * 8;
}
return val;
}
int main() {
int num = 45;
cout <<"after conversion value is "<<convert(num);
}输出
如果我们运行以上代码,它会生成以下输出
after conversion value is 37
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP