1. 程式人生 > >二進位制加法(算導課後習題)

二進位制加法(算導課後習題)

#include<stdio.h>
#include<iostream>
#include<cstring>

#define MAXN 300+10
using namespace std;
void Add(char s1[],char s2[])
{
    int num1[MAXN] = {0},num2[MAXN] = {0};//對陣列num1和num2進行初始化,初始化為零;
    int len1 = strlen(s1);//標頭檔案#include<cstring>控制strlen函式;
    int len2 = strlen(s2);
    int
i=0,j=0; for(i = len1-1,j = 0;i >= 0;i--) num1[j++] = s1[i] - '0'; for(i = len2-1,j = 0;i >= 0;i--) num2[j++] = s2[i]-'0'; // for(i = 0;i < MAXN;i++) { num1[i] += num2[i]; if(num1[i] >= 2) { num1[i] -=2;//num[i] = num[i] - 2;
num1[i+1]++; } } //在倒敘輸出num1[i]時去掉此陣列後邊多餘的0; int wh = MAXN-1; while(num1[wh] == 0) wh--;//找到非零的位置用wh表示 for(int k = wh;k >= 0;k--) printf("%d",num1[k]); printf("\n"); } int main() { char s1[MAXN],s2[MAXN]; scanf("%s%s",s1,s2); Add(s1,s2);//呼叫Add函式
return 0; }