導航:首頁 > 編程知識 > 編程高精度加法怎麼寫char

編程高精度加法怎麼寫char

發布時間:2023-08-30 01:58:48

『壹』 c語言編程 高精度加減法

本來以為很簡單,結果寫著寫著發現也不簡單,用了2個小時。
#include<stdio.h>
#include <conio.h>
#include <string.h>
#include "stdlib.h"

void main()
{
int n=0,i=0,j=0,k=0,b=0;
char a[3][500]={0};
int n1=0,n2=0;
char s[500]={0};
int n3=0;
int c=0,c1=0;
int temp=0;
char op;
char str[1001]={0};
char *result;

scanf("%d",&n);
result=(char *)malloc(501*n);//根據輸入的n申請內存空間
*result='\0';

/*每次循環都要初始化*/
for(;i<n;i++)
{
//gets(str);
for(j=0;j<500;j++)
{
a[0][j]='\0';a[1][j]='\0';a[2][j]='\0';
s[j]='\0';
str[j]='\0';
str[1000-j]='\0';
}
c=0;c1=0;
k=0;
n1=0;n2=0;n3=0;

/*分離輸入的字元串*/
scanf("%s",&str);
for( j=0;str[j];j++ )
{
if( str[j]!='+' && str[j]!='-')
a[k][j-n1]=str[j];
else
{
op=str[j];
k=1;
n1=strlen(a[0])+1;
}
}//for j
n1-=2;
n2=strlen(a[1])-1;
n3=n1>n2?n1:n2;

/*計算加法*/
if(op=='+')
{
for(;n1>=0&&n2>=0;n1--,n2--,n3--)
{
temp=a[0][n1]+a[1][n2]-96;
temp+=c;
if(temp>=10)
{
s[n3]=temp%10+48;
c=1;
}
else
{
s[n3]=temp+48;
c=0;
}
}//for
while(n1>=0)
{
temp=a[0][n1]-48;
temp+=c;
if(temp==10)
{
s[n3]=48;
c=1;
}
else
{
s[n3]=temp+48;
c=0;
}
n1--;
n3--;
}//while n1
while(n2>=0)
{
temp=a[1][n2]-48;
temp+=c;
if(temp==10)
{
s[n3]=48;
c=1;
}
else
{
s[n3]=temp+48;
c=0;
}
n2--;
n3--;
}//while n2
if(c)
strcat(result,"1");
strcat(result,s);
strcat(result,"\n");
}//if op

/*計算減法*/
else
{ /*保證減數大於被減數
*如果被減數大於減數,則交換2數,並設置變數
*/
if(strcmp(a[0],a[1])<0)
{
//a[2]=a[0];a[0]=a[1];a[1]=a[2];
for(b=0;b<3;b++)
{
j=(b+2)%3;
for(k=0;k<=n2;k++)
a[j][k]=a[b][k];
}
n2=n1;n1=n3;
c1=1;//正為0,負為1
}

/*計算減法*/
for(;n2>=0;n1--,n2--,n3--)
{
temp=a[0][n1]-a[1][n2];
temp-=c;
if(temp>=0)
{
s[n3]=temp+48;
c=0;
}
else
{
s[n3]=temp+58;
c=1;
}
}//for
while(n1>=0)
{
temp=a[0][n1]-48;
temp-=c;
if(temp>=0)
{
s[n3]=temp+48;
c=0;
}
else
{
s[n3]=temp+58;
c=1;
}
n1--;
n3--;
}

if(c1)
strcat(result,"-");

/*消除減法結果高位的0*/
j=0;
while(s[j]==48)
j++;
strcat(result,s+j);
strcat(result,"\n");
}//else op
}//for i
printf("%s",result);
getch();
}

閱讀全文

與編程高精度加法怎麼寫char相關的資料

熱點內容
魅族pro5自帶瀏覽器怎麼升級 瀏覽:342
為什麼用數據還是載入慢 瀏覽:171
監控下面有網路如何隔離 瀏覽:748
前台中jrequestjson 瀏覽:435
怎麼在word里粘貼xls文件 瀏覽:710
買火車票什麼網站 瀏覽:757
jsp的六大 瀏覽:216
圖文數據要如何導入資料庫 瀏覽:207
軟體數據刪了恢復怎麼弄 瀏覽:517
小米筆記本電腦共享文件 瀏覽:812
cad字體文件夾添加國標字體 瀏覽:938
電腦輸出pdf文件有什麼用 瀏覽:695
微信滿人 瀏覽:585
js點擊按鈕下載圖片 瀏覽:922
數據有效性哪裡設置的 瀏覽:171
orl刪除表的資料庫 瀏覽:353
cad文件0位元組可以修復么 瀏覽:675
瀏覽器下載的軟體在文件中怎麼找 瀏覽:906
怎麼把word圖片變小 瀏覽:278
cf的文件夾 瀏覽:556

友情鏈接