C++ cout的轉換格式輸出(八進位和十六進位),cout十六進位
// hex,oct 輸出#include<iostream>using namespace std;int main(){int chest = 42, waist = 42, inseam = 42;cout << "chest = " <<chest << " (decimal for 42)" << endl;cout << hex;// manipulator for changing number basecout << "waist = " << waist << " (hexadecimal for 42)" << endl;cout << oct;//manipulator for changing number basecout << "inseam = " << inseam << " (octal for 42)" << endl;return 0;}
C++中怎完成十六進位到八進位的轉換
電腦內都是2進位,輸入輸出時才體現出 其它進位。
#include <iostream>
#include <iomanip>
using namespace std;
main(){
int x;
cout << "input hex data " << endl;
cin >> hex >> x; // 這個方法輸入的數處理為16進位
cout << oct << x << endl; // 這個方法輸出的數處理為8進位
}
順便說一下:C 語言輸入輸出 %x 格式 是 16 進位, %o 是 8 進位。
使用者輸入一個十進位正整數,然後分別轉換成為位元、八位元與十六進位數輸出(是C++,不是C)
#include<iostream>
using namespace std;
int main()
{
int a,b,c,d;
cout<<"請輸入待轉換的數:";
cin>>a;
//二進位分別計算每一位
if(a==0)cout<<a;
b=a;c=0;d=1;
while(b!=0)
{
c+=(b%2)*d;//依次把b除以2的餘數寫在c的對應位置上
b=b/2;
d*=10;
}
cout<<c<<endl;
//八進位和十六進位使用格式化輸出即可,oct表示八進位,hex表示十六進位
cout<<oct<<a<<endl;
cout<<hex<<a<<endl;
}
如果有不懂請追問。