当前位置:网站首页>C语言 简单易懂的高精度加法
C语言 简单易懂的高精度加法
2022-07-06 07:12:00 【小妞无语】
场景
我想大家在小学刚学开始学习列式计算时,应该都有被老妈拎着耳朵说怎么又忘记进一了,都幻想有个机器可以帮自己计算,现在你算看到的高精度加法就是这个原理。
问题描述
它关键的点有简单的几个
1.数据存储问题
当我们的 int 和 longlong也没有办法满足这个数的存储大小时我们该怎么办?
首先想到的就是拆分啊,把一个很长很长的数字拆成一位又一位这样不就方便储存了,这就用到了数组存储的方法
2.拆分之后怎么进行运算
这就简单多了,就和我们小学学的一样满十进一原则
知道这些就ok了,下面看看代码的展示吧!
代码展示
#include<stdio.h>
#include<string.h>
char s1[505],s2[505];
int a[505],b[505],c[505];//定义里面外面都可以
int main()
{
int la,lb,lc;
scanf("%s",s1);
scanf("%s",s2);//由于不知道数字的长度,先将其定义为字符型·
la=strlen(s1);//直接计算长度没有‘/0’
lb=strlen(s2);
for(int i=0;i<la;i++)
a[la-i]=s1[i]-'0';//将字符数组变成数字型便于计算,并使其倒序存储
for(int i=0;i<lb;i++)
b[lb-i]=s2[i]-'0';
lc=(lb>la)?(lb+1):(la+1);//运用三目运算符,由于不论数有多大最大就是最长长度+1
for(int i=0;i<=lc;i++)
{
c[i]+=a[i]+b[i];//由于c[i]可能不为0,所以也要参与累加
c[i+1]=c[i]/10;//进位
c[i]=c[i]%10;//取余
}
if(c[lc]==0&&lc>0)//如果最高为0,就将其去除
lc--;
for(int i=lc;i>0;i--)
printf("%d",c[i]);
return 0;
}
边栏推荐
猜你喜欢
UWA pipeline version 2.2.1 update instructions
Idea console color log
Week6 weekly report
Leetcode 78: subset
How to find a medical software testing institution? First flight software evaluation is an expert
Configure raspberry pie access network
Proteus -- Serial Communication parity flag mode
MVVM of WPF
Establishment and operation of cloud platform open source project environment
Huawei equipment configuration ospf-bgp linkage
随机推荐
[daily question] 729 My schedule I
顶测分享:想转行,这些问题一定要考虑清楚!
Project GFS data download
多线程和并发编程(二)
The difference between get and post request types
How to find a medical software testing institution? First flight software evaluation is an expert
MVVM of WPF
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
简单描述 MySQL 中,索引,主键,唯一索引,联合索引 的区别,对数据库的性能有什么影响(从读写两方面)
Multithreading and concurrent programming (2)
TS基础篇
[advanced software testing step 1] basic knowledge of automated testing
[hot100] 739. Température quotidienne
Setting and using richview trvstyle template style
Librosa audio processing tutorial
Solution to the problem of breakthrough in OWASP juice shop shooting range
leetcode841. 钥匙和房间(中等)
网络安全基础介绍
MPLS experiment
Hydra common commands