#include <iostream>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
int main(){
char Pbuf8[9]={"01100000"};
char Mbuf4[10]={"01110000"};
int num=0;
char Snum[9]="0";
int carry=0;
for(int c=7;c>=0;c--){
//Convert a string to a number and add
num=(Pbuf8[c]-'0')+(Mbuf4[c]-'0')+carry;
//binary addition
if(num==1){
Snum[c]=num;
carry=0;
}else if(num==2){
num=0;
carry=1;
Snum[c]=num;
}else if(num==3){
num=1;
carry=1;
Snum[c]=num;
}
//Convert num to string and store in Snum
sprintf(Snum, "%d", num);
}
//output
printf("%s",Snum);
return 0;
}
Calculate and output the sum of Pbuf8 and Mbuf4.
I want to output '00001011' but '1' is output.
If there is no 'sprintf(number, "%d", number);' does not exist, 'rr' is output.
How do I get the value I want?
You have 3 minor bugs in your code.
num+'0'
The corrected code will look like:
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <stdio.h>
int main(){
char Pbuf8[9]={"01100000"};
char Mbuf4[10]={"01110000"};
int num=0;
char Snum[9]="00000000";
int carry=0;
for(int c=7;c>=0;c--){
//Convert a string to a number and add
num=(Pbuf8[c]-'0')+(Mbuf4[c]-'0')+carry;
//binary addition
if(num==1){
Snum[c]=num+'0';
carry=0;
}else if(num==2){
num=0;
carry=1;
Snum[c]=num+'0';
}else if(num==3){
num=1;
carry=1;
Snum[c]=num+'0';
}
//Convert num to string and store in Snum
//sprintf(Snum, "%d", num);
}
//output
printf("%s",Snum);
return 0;
}