当前位置:网站首页>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;
}
边栏推荐
- 1189. Maximum number of "balloons"
- UDP攻击是什么意思?UDP攻击防范措施
- 开源的网易云音乐API项目都是怎么实现的?
- Win10 64 bit Mitsubishi PLC software appears oleaut32 DLL access denied
- PCL实现选框裁剪点云
- Detailed explanation | detailed explanation of internal mechanism of industrial robot
- The differences and advantages and disadvantages between cookies, seeion and token
- [daily question] 729 My schedule I
- Thought map of data warehouse construction
- How are the open source Netease cloud music API projects implemented?
猜你喜欢
3. Business and load balancing of high architecture
变量的命名规则十二条
JDBC学习笔记
Win10 64 bit Mitsubishi PLC software appears oleaut32 DLL access denied
Blue Bridge Cup zero Foundation National Championship - day 20
Cookie技术&Session技术&ServletContext对象
Lesson 12 study notes 2022.02.11
[server data recovery] case of offline data recovery of two hard disks of IBM server RAID5
Visitor tweets about how you can layout the metauniverse
Wechat official account infinite callback authorization system source code, launched in the whole network
随机推荐
【Hot100】739. 每日溫度
leetcode59. 螺旋矩阵 II(中等)
The author is dead? AI is conquering mankind with art
【JDBC】快速入门教程
Zhongqing reading news
Yield method of tread
leetcode704. 二分查找(查找某个元素,简单,不同写法)
Résumé de la structure du modèle synthétisable
supervisor 使用文档
Uni app practical project
UDP攻击是什么意思?UDP攻击防范措施
The differences and advantages and disadvantages between cookies, seeion and token
变量的命名规则十二条
数据仓库建设思维导图
How are the open source Netease cloud music API projects implemented?
[JDBC] quick start tutorial
树莓派串口登录与SSH登录方法
JDBC learning notes
The psychological process from autojs to ice fox intelligent assistance
Oracle数据库11gr2使用tde透明数据加密报错ora28353,如果运行关闭wallet会报错ora28365,运行打开wallet就报错ora28353无法打开wallet