c++中八进制数如何转换成十进制数?
希望能够详细解答,谢啦!
// Note:Your choice is C++ IDE
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int j,s,k=0;
int a[20];
cout<<"输入一个八进制数 "<<endl;
cin>>s;
while(s!=0)
{
j=s%10; //求s的各个位数
a[k]=j; //将s的各个位数赋值给a[]
k=k+1; //计算s是举尺一个几位数
s=s/10;
}
s=0;
for(j=k-1;j>=0;j--)
{
s=pow(8,j)*a[j]+s;
}
cout<<码烂"转换为十进制为 "<<s;
return 0;
}
你看看哪个好理解,希望迟答漏给我加分;哈
加权就一下就可源丛以了。
比如:(22347)八=2*8^4+2*8^3+3*8^2+4*8^1+7=8192+1024+192+32+7=9447
可以直接用C++里面的数制转换,不过我想你要的不是这个。
看看下面的做法:
把八进制数放入一个数组中(可通过求余),然后再按上式计算即可山瞎。
下面是一个逗裂空例子:
#include<iostream.h>
#include<math.h>
void main()
{
int ba; //八进制数
int n; //十进制数
int temp; //临时变量
int a[30];
int count=0;
n=0;
cout<<"请输入你的八进制数:";
cin>>ba;
temp=ba;
while(temp!=0)
{
a[count]=temp%10;
temp=temp/10;
count++;
for(int i=count-1;i>=0;i--)
{
n+=a[i]*(int)pow(8,i);
}
cout<<"转换后的数是:"<<n<<endl;
}
#include <iostream>
using namespace std;
int main()
{
int o=0,d=123456;//o--八进制数,d--十进制数
char ch[128]={0};//中介字符迟皮清串
itoa(d,ch,8);//将十进制 d 转换为 八进码前制,并存储在字符串ch中
o=atoi(ch);//将字符串ch转换为数值握孝,其实如果不转换也可以直接输出ch得到结果
cout<<o;//输出结果
return 0;
}
//
Note:Your
choice
is
C++
IDE
#include
<iostream>漏悄
#include
<cmath>
using
namespace
std;
int
main()
{
int
j,s,k=0;
int
a[20];
cout<<"输入一个八进制数
"<<endl;
cin>>s;
while(s!=0)
{
j=s%10;
//求s的各个位数
a[k]=j;
//将s的各个位数赋值给a[]
k=k+1;
//计算s是一个几位数
s=s/10;
}
s=0;
for(j=k-1;j>=0;j--)
{
s=pow(8,j)*a[j]+s;
}
cout<<"返灶渣转换为十进制为
"<<s;
return
0;
}
你看看哪个好理解,希望给我加分;辩州哈
#include<iostream>弯亩
using namespace std;
string s;
int sum;
int main()
{
cin >> s;
for(int i = 0; i < s.length(); i++)
{
sum = sum * 8 + s[i] - '档闹弊0' ;
}
cout<<sum<<行族endl;
return 0;
}