大整數的四則運算(C語言實現)(1)——大整數的輸入處理

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/FelikZhang/article/details/78841341

要想對大整數進行精確的四則運算,首先要解決大整數的輸入問題,大整數的輸入不能基本的變量類型去接收,而應當使用字符串,下面的代碼使用順序表實現了大整數的輸入處理,存儲及輸出操作。同時對輸入數據前導有零的情況進行處理。


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct bigint{
	char *num;	//大整數數據域 
	int sign;	//大整數符號位 
	int digit;	//大整數位數 
}BIGINT;

BIGINT ScanfBigInt();	//大整數的讀取處理函數 
void PrintBigInt(BIGINT BigInt);//大整數的輸入輸出函數

int main(void)
{
	BIGINT BigInt;
	BigInt=ScanfBigInt();
	
	printf("\n\n回到了主函數!\n\n");
	PrintBigInt(BigInt);
	
	printf("處理完可能的前導0後,這是一個%d位數\n",BigInt.digit);//測試代碼 
	
	free(BigInt.num);
	return 0;
}

BIGINT ScanfBigInt()
{
	BIGINT BigInt;
	int bit,cnt;
	int i,j,k;
	int num;
	char *tempnum=NULL;
	printf("請輸入最大數的位數:"); 
	scanf("%d",&num);
	tempnum=(char *)malloc(sizeof(char)*(num+2));//多兩個空間,一個預留存負號,一個存'\0' 
	BigInt.num=(char *)malloc(sizeof(char)*(num+2));
	printf("請輸入大整數:");
	scanf("%s",tempnum);
	cnt=strlen(tempnum);
	BigInt.digit=cnt;	//確定大整數的位數
	if(tempnum[0]=='-'){//確定大整數的正負 
		BigInt.sign=-1;
		tempnum[0]='0';//把負號換成字符0,後面統一處理 
	}
	else{
		BigInt.sign=1;
	}
	for(i=0,j=cnt-1;i<cnt;j--,i++){//倒序保存大整數的值 
		BigInt.num[j]=tempnum[i];
	}
	//處理可能存在的前導0 
	for(k=BigInt.digit-1;k>=0 && BigInt.num[k]=='0';k--);
	if(k<BigInt.digit-1){//這個數有前導0 
		BigInt.digit=k+1;
	}
	if(k==-1){//這個數是0
		BigInt.digit=1;
	}
	free(tempnum);
	return BigInt;
}

void PrintBigInt(BIGINT BigInt)
{
	int j;
	if(BigInt.sign==-1){
		printf("-");
	}
	for(j=BigInt.digit-1;j>=0;j--){
		printf("%c",BigInt.num[j]);
	}
	printf("\n輸出結束\n");
}

博主學生一枚,文章內容描述有不當之處歡迎大家指正,謝謝。

看完這一篇,點這裏看下一篇文章:大整數的加減法運算


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章