Your code already stores input as an array of char. Every char is an integral value, so each char value can be stored in an int.
Your code already stores input as an array of char. Every char is an integral value, so each char value can be stored in an int.
This is my new code but there are still bugs in it. Could you please tell me what's wrong with it.
Code:# include<stdio.h> #include <string.h> char x[32]; char y[32]; char z[32]; char b[32]; int c[32]; int a,s; char sum[32]; int carry; main() { printf("Please input the first binary number.\n"); scanf("%s", x); printf("Please input the second binary number.\n"); scanf("%s", y); for(a=31;a>=0;a--){ if (x[a]=='0') b[a]=0; else if (x[a]=='1') b[a]=1;} for(a=31,s=0;a>=0;a--,s++){ if (y[a]=='0') c[a]=0; else if (y[a]=='1') c[a]=1;} carry=0; for(a=31;a>=0;a--){ sum[a]=b[a]+c[a]+carry; if (sum[a]>1){ sum[a]=sum[a]-2; carry=1;} else{ carry=0;} } for(a=0;a<=31;a++) printf("%d", sum[a]); }
That's your job. Why don't you tell us what part doesn't seem to work right?Why are all of those global when you only have one function anyway?Code:char x[32]; char y[32]; char z[32]; char b[32]; int c[32]; int a,s; char sum[32]; int carry;Use:Code:main()Then return 0; at the end of main.Code:int main( void )What happens if I enter 8 digits instead of 32?Code:{ printf("Please input the first binary number.\n"); scanf("%s", x); printf("Please input the second binary number.\n"); scanf("%s", y); for(a=31;a>=0;a--){
What happens if both of the end digits are 1? ... and you have a carry?
Quzah.
Hope is the first step on the road to disappointment.
Hope is the first step on the road to disappointment.
If only there were some way to determine the end of a string so you don't have to cycle through every index of each array ...
And some suggestions:
- Fix the indentation/layout of your code so it's easier to read
- Make your variable names meaningful so the code is easier to read
- You drag the variable 's' around and manipulate it, but never use it for anything
- Heed Quzah's advice about the proper form of "main()"
Yes, I actually noticed that just now while writing my own version of this program.
I wonder if the OP has considered making a loop that would cycle through the character array and count until it reached a certain (special) character. Perhaps they could use this count for something helpful.
Never a time like the present to learn. C-Style Strings tutorial
Let's see if you have what it takes. By answering the questions I will ask, we will approach the code I mentioned together.
Question 1: In 'C', what is the difference between a string and a character array?
What is this, Are you smarter than a 5th grader? I choose c, wait....d**n.