最近比較有時間 , 在學長建議下 , 開始寫些跟工作相關的技術文章 , 當作複習 , 也順便筆記 , 年紀大了 , 漏電速度比較快 , 哈 XD
技巧
利用陣列方式儲存輸入數字進行運算 , 共分為3步驟
Step1 : 輸入字串轉換為數字
ex String[] = "1234"
String[0] = '1' , String[1] = '2' , String[2] = '3' , String[3] = '4'
則 Big[3] = '1' - '0' = 1 , Big[2] = 2 , Big[1] = 3 , Big[0] = 4 , 故必須先金輸入字串進行轉換
Step2 : 逐筆相加 , 有進位設定Carry
ex Big_A[1] = 8 , Big_A[0] = 3
Big_B[1] = 7 , Big_B[0] = 9
則 Big_A[0] + Big_B[0] = 3 + 9 = 11 = Result
(Result / 10) > 0 因此設定 Carry[0] = 1 , 代表有進位
接著 Result = (Result % 10)
Step3 : 進位處理
程式碼 :
/* Source Code By Christine , 2016-08-31 */
#include "stdafx.h"
#include "string.h"
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 200
void Read_from_String_to_Int( char* pcInput , int* iBig , int* iBigLen )
{
int i;
int iStrLen = strlen(pcInput);
*iBigLen = iStrLen;
for( i = 0 ; i < iStrLen ; i++ )
{
iBig[iStrLen-i-1] = (pcInput[i] - '0');
}
}
void Process_Addition( int* iBig1 , int* iBig2, int* iBigResult , int iBigLen1, int iBigLen2)
{
int iLen;
int i;
int iResult;
int iCarry[MAX_LEN];
for( i = 0 ; i < MAX_LEN ; i++ ) iCarry[i] = 0;
// Step1 : 確認長度
if(iBigLen1 > iBigLen2) iLen=iBigLen1; else iLen=iBigLen2;
// Step2 : 逐位相加
for( i = 0 ; i < iLen ; i++ )
{
iResult = ( iBig1[iLen-i-1] + iBig2[iLen-i-1]);
if((iResult/10) > 0 )iCarry[iLen-i-1]++;
iBigResult [iLen-i-1] = (iResult%10);
}
// Step3 : 進位處理
for( i = 0 ; i < iLen ; i++ )
{
if( iCarry[i] != 0 )
{
iBigResult[i+1]++;
if((iBigResult[i+1]/10) > 0 )iCarry[i+2]++;
iBigResult[i+1] = (iBigResult[i+1]%10);
}
}
// Step4 : 結果顯示
printf("Addition Result : ");
for( i = 0 ; i < iLen ; i++ )
{
printf("%d",iBigResult[iLen-i-1]);
}
printf("\n\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
char cInput[MAX_LEN];
int iBig1[MAX_LEN];
int iBig2[MAX_LEN];
int iBigLen1 = 0;
int iBigLen2 = 0;
int iBigResult[MAX_LEN];
int i;
for( i = 0 ; i < MAX_LEN ; i++ )
{
cInput[i] = 0;
iBig1[i] = 0;
iBig2[i] = 0;
iBigResult[i] = 0;
}
printf("Value1 : ");
scanf("%s",&cInput);
Read_from_String_to_Int(cInput,iBig1,&iBigLen1);
printf("Value2 : ");
scanf("%s",&cInput);
Read_from_String_to_Int(cInput,iBig2,&iBigLen2);
Process_Addition(iBig1,iBig2,iBigResult,iBigLen1,iBigLen2);
printf("\n");
system("pause");
return 0;
}
執行測試結果 :
留言列表