C++ cout的轉換格式輸出(八進位和十六進位),cout十六進位

來源:互聯網
上載者:User

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;
}

如果有不懂請追問。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.