我的代碼只能添加兩個Hedecimal數字,但我們應該添加兩個以上,這樣的輸入就像這個FFFFFFFFFFFFF + 1 + 2 + 3 + 4可能更多addtion。我們可以使用運算符重載。 這是我的代碼。超過兩個數字十六進制加法
#include <iostream>
#include <string>
#include<cstddef>
#include<cstring>
using namespace std;
int changeint(char a)
{
switch(a)
{
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'A': return 10;
case 'B': return 11;
case 'C': return 12;
case 'D': return 13;
case 'E': return 14;
case 'F': return 15;
}
}
char changechar(int a)
{
switch(a)
{
case 0: return '0';
case 1: return '1';
case 2: return '2';
case 3: return '3';
case 4: return '4';
case 5: return '5';
case 6: return '6';
case 7: return '7';
case 8: return '8';
case 9: return '9';
case 10:return 'A';
case 11:return 'B';
case 12:return 'C';
case 13:return 'D';
case 14:return 'E';
case 15:return 'F';
}
}
int main()
{
string input,input_one,input_two;
int count_one,count_two;
cin>>input;
count_one=input.find('+',0);
count_two=input.length();
input_one=input.substr(0,count_one);
input_two=input.substr(count_one+1,count_two-count_one-1);
char a[1000];
char b[1000];
char c[1001];
a[1000]=0;
strcpy(a,input_one.c_str());
b[1000]=0;
strcpy(b,input_two.c_str());
int A[1000],B[1000],C[1001],i,lena=0,lenb=0,lenc=1000;
for(i=0;i<1001;i++)
C[i]=0;
for(i=0;i<1000;i++)
{
A[i]=0;
B[i]=0;
}
while(a[lena]!=0) lena++;
while(b[lenb]!=0) lenb++;
for(i=0;i<lena;i++)
A[lena-i-1]=changeint(a[i]);
for(i=0;i<lenb;i++)
B[lenb-i-1]=changeint(b[i]);
for(i=0;i<1000;i++)
{
C[i]=C[i]+A[i]+B[i];
if(C[i]>15)
{
C[i]=C[i]-16;
C[i+1]++;
}
}
for(i=999;i>=0;i--)
{
if(C[i]==0) lenc--;
else break;
}
if(lenc==0)
lenc=1;
for(i=0;i<lenc;i++)
c[i]=changechar(C[lenc-i-1]);
for(i=0;i<lenc;i++)
cout<<c[i];
return 0;
}
感謝您的幫助。
您可以通過使用'文本的數字轉換爲數字INT數= A - 「0」;'。不需要switch語句。你也可以通過有一個字符數組來查找。 –
非常感謝,我重寫了它。 –