0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

桁の長い数を足し算するC言語のプログラムを作ってみた

Last updated at Posted at 2020-09-05

間違ってるかもしれないけど本を参考にしてとりあえず作ってみた。

test.c
/*
 * BCD演算
 */
#include <stdio.h>
#include <string.h>

#define LEN 255      /* 最大桁数 */

void sub(char* num1, char* num2)
{
	char ans[LEN + 1];  /* 加算結果 */
	int i, sum, carry, n1, n2;
	int len1 = strlen(num1); int len2 = strlen(num2);
	char zero[LEN];
	zero[0] = '\0';

	if (len1 >= len2) {
		for (int k = 0; k < len1 - len2; k++) {
			strcat_s(zero, LEN, "0");
		}
	
		strcat_s(zero, LEN, num2);
		num2 = zero;

		carry = 0;   /* 繰り上げ */
		for (i = len1 - 1; i >= 0; i--) {  /* 下位から1桁ずつ足し算していく */
			n1 = num1[i] - '0';
			n2 = num2[i] - '0';

			sum = n1 + n2 + carry;
			if (sum >= 10) {   /* 繰り上げ発生 */
				sum -= 10;
				carry = 1;
			}
			else {
				carry = 0;
			}

			ans[i] = (char)(sum + '0');
		}
		ans[len1] = '\0';

	}
	else {
		for (int k = 0; k < len2 - len1; k++) {
			strcat_s(zero, LEN, "0");
		}
		strcat_s(zero, LEN, num1);
		num1 = zero;

		carry = 0;   /* 繰り上げ */
		for (i = len2 - 1; i >= 0; i--) {  /* 下位から1桁ずつ足し算していく */
			n1 = num1[i] - '0';
			n2 = num2[i] - '0';

			sum = n1 + n2 + carry;
			if (sum >= 10) {   /* 繰り上げ発生 */
				sum -= 10;
				carry = 1;
			}
			else {
				carry = 0;
			}

			ans[i] = (char)(sum + '0');
		}
		ans[len2] = '\0';

	}



	/* 加算数と被加算数の表示 */
	printf("  %s\n", num1);
	printf("+ %s\n", num2);

	printf(" ");

	/* 最上位桁で繰り上げが発生していたら,"1"を出力する */
	if (carry)
		printf("1");
	else
		printf(" ");

	printf("%s\n\n", ans);
}

int main(void)
{
	char num1[LEN], num2[LEN];
	printf("数値1を入力してください");
	scanf_s("%s", num1, LEN);

	int c;
	while ((c = getchar()) != '\n');

	printf("数値2を入力してください");
	scanf_s("%s", num2, LEN);
	//printf("num2->%s\n", num2);

	sub(num1, num2);

	return 0;
}

0
0
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?