Skip to content

Instantly share code, notes, and snippets.

@tsunakan
Last active July 10, 2021 03:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tsunakan/46c6668f9861d7fb57aad490e3b13a60 to your computer and use it in GitHub Desktop.
Save tsunakan/46c6668f9861d7fb57aad490e3b13a60 to your computer and use it in GitHub Desktop.
桁数制限のない加算器(正の整数のみ)
#include <stdio.h>
#include <string.h>
#define DIGIT 100
void AddBCD(char res[],char st[],char st2[]);
void ReverseDigit(char st[]);
int main (void)
{
char st[DIGIT];
char st2[DIGIT];
char res[DIGIT];
res[0]='0';
printf("足す数を入力\n");
scanf("%s",st);
printf("もう1個入力\n");
scanf("%s",st2);
AddBCD(res,st,st2);
printf("合計\n");
printf("%s\n\n",res);
return 0;
}
//足し算のひっ算 res[] = st[] + st2[]
//配列の1要素が1ケタ
void AddBCD(char res[DIGIT],char st[DIGIT],char st2[DIGIT])
{
int i = 0;
int sum = 0;
char flag = 0;
int carry = 0;
//桁上がりするとst[-1]を使ってしまうため
//リトルエンディアンにしてから足し算
ReverseDigit(st);
ReverseDigit(st2);
//どちらの桁もあるとき
while(!flag)
{
sum = (int)(st[i]-'0')+(int)(st2[i]-'0')+carry;
carry = 0;
//桁上がりの処理
if(sum>=10)
{
carry = 1;
sum -= 10;
}
res[i]= (char)(sum+'0');
i++;
//片方(両方)の桁に値がなくなったらwhileを抜ける
if(st[i]=='\0' || st2[i]=='\0')
{
flag = 1;
}
}
//片方(両方)の桁がNULLになってからの処理
if(st[i]=='\0'&&st2[i]=='\0'&&carry)
{
res[i]='1';
i++;
carry=0;
}
//片方の桁がまだ残ってる時の処理
else if(st[i]=='\0')
{
while(st2[i]!='\0')
{
sum = (int)(st2[i]-'0')+carry;
carry=0;
if(sum>=10)
{
carry = 1;
sum -= 10;
}
res[i]=(char)(sum+'0');
i++;
}
}
//上のelse if (st[i]=='\0')と同じことをしてる
else if(st2[i]=='\0')
{
while(st[i]!='\0')
{
sum = (int)(st[i]-'0')+carry;
carry=0;
if(sum>=10)
{
carry = 1;
sum -= 10;
}
res[i]=(char)(sum+'0');
i++;
}
}
if(carry)
{
res[i]='1';
i++;
}
res[i]='\0';
//最後に答えをビックエンディアンに戻す
ReverseDigit(res);
}
//文字列を反転する
//桁上がりした時に配列に入りきらないst[-1]
//リトルエンディアンにして計算する
void ReverseDigit(char st[DIGIT])
{
int i;
int N=0;
char st2[DIGIT];
for(i=0;st[i]!='\0';i++)
{
N++;
}
for(i=0;i<N;i++)
{
st2[i]=st[N-i-1];
}
st2[N]='\0';
for(i=0;st[i]!='\0';i++)
{
st[i]=st2[i];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment