題目描述:寫(xiě)出一個(gè)程序翘县,接受一個(gè)十六進(jìn)制的數(shù)值字符串最域,輸出該數(shù)值的十進(jìn)制字符串。(多組同時(shí)輸入 )
輸入描述:輸入一個(gè)十六進(jìn)制的數(shù)值字符串锈麸。
輸出描述:輸出該數(shù)值的十進(jìn)制字符串镀脂。
我的解題:
# include<iostream>
# include<cmath>
using namespace std;
int main()
{
string input;
while( getline(cin, input) )
{
int res = 0;
int k = 0;
for( int i=input.length()-1;i>1;i-- )
{
int temp = 0;
if( input[i] >= 'A' && input[i] <= 'F')
temp = input[i]-'A'+10;
else
temp = input[i]-'0';
res += temp*pow(16,k);
k++;
}
cout << res << endl;
}
return 0;
}
別人解法:
#include <iostream>
using namespace std;
int main()
{
int a;
while(cin>>hex>>a){
cout<<a<<endl;
}
}
cin、cout 默認(rèn)進(jìn)制:
默認(rèn)狀態(tài)下掐隐,數(shù)據(jù)按十進(jìn)制輸入輸出狗热。如果要求按八進(jìn)制或十六進(jìn)制輸入輸出,在cin或cout中必須指明相應(yīng)的數(shù)據(jù)形式虑省,oct為八進(jìn)制匿刮,hex為十六進(jìn)制,dec為十進(jìn)制探颈。
int i, j, k, l;
cin >> oct >> i; //輸入為八進(jìn)制數(shù)
cin >> hex >> j; //輸入為十六進(jìn)制數(shù)
cin >> k; //NOTE:輸入仍為十六進(jìn)制數(shù)
cin >> dec >> l; //輸入為十進(jìn)制數(shù)
cout << hex << i << endl;//輸出為十六進(jìn)制數(shù)
cout << oct << l << endl;//輸出為八進(jìn)制數(shù)
cout << j << endl; //NOTE:輸出仍為八進(jìn)制數(shù)
cout << dec << endl; //恢復(fù)十進(jìn)制輸出狀態(tài)
NOTE:將cin或者cout的進(jìn)制數(shù)修改后熟丸,后面的cin/cout會(huì)保持修改后的進(jìn)制數(shù)