導航:首頁 > 編程知識 > 編程高精度加法怎麼寫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相關的資料

熱點內容
發送手機里的錄音文件在哪裡 瀏覽:866
js獲取下一個兄弟元素 瀏覽:293
js模板引擎原理 瀏覽:72
linuxo文件運行 瀏覽:713
什麼免費備份數據 瀏覽:342
測量大師導入底圖找不到文件 瀏覽:313
小紅傘安裝程序要求版本6 瀏覽:799
全民k歌pcm文件夾 瀏覽:224
c圖片寫入資料庫 瀏覽:466
c串口程序 瀏覽:500
中農金融注冊app有哪些 瀏覽:629
回收站文件清理不在電腦上有痕跡 瀏覽:886
dx版本更新 瀏覽:738
主機集群教程 瀏覽:939
蘋果6英版好不好 瀏覽:959
nodejs抓取網站音頻 瀏覽:772
app上下載的軟體在哪裡 瀏覽:36
起凡保存的照片在哪個文件夾 瀏覽:354
數學建模如何把模型編程 瀏覽:176
ug找不到指定的許可文件 瀏覽:850

友情鏈接