当前位置:网站首页>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;
}
边栏推荐
- A brief introduction of reverseme in misc in the world of attack and defense
- OpenGL ES 学习初识(1)
- ROS learning_ Basics
- 18. Multi level page table and fast table
- The psychological process from autojs to ice fox intelligent assistance
- leetcode841. Keys and rooms (medium)
- 变量的命名规则十二条
- 多线程和并发编程(二)
- Due to high network costs, arbitrum Odyssey activities are suspended, and nitro release is imminent
- Cookie Technology & session Technology & ServletContext object
猜你喜欢
Babbitt | metauniverse daily must read: the group image of Chinese Internet enterprises pouring into metauniverse: "there are only various survival desires, and there is no ambition for forward-lookin
微信脑力比拼答题小程序_支持流量主带最新题库文件
指尖上的 NFT|在 G2 上评价 Ambire,有机会获得限量版收藏品
leetcode841. 钥匙和房间(中等)
The first Baidu push plug-in of dream weaving fully automatic collection Optimization SEO collection module
Short video, more and more boring?
Wechat official account infinite callback authorization system source code, launched in the whole network
A brief introduction of reverseme in misc in the world of attack and defense
(4) Web security | penetration testing | network security web site source code and related analysis
Hydra common commands
随机推荐
Solution to the problem of breakthrough in OWASP juice shop shooting range
Interface automation test framework: pytest+allure+excel
The psychological process from autojs to ice fox intelligent assistance
GET 和 POST 请求类型的区别
SSM学习
RichView TRVStyle 模板样式的设置与使用
Bio model realizes multi person chat
Compile, connect -- notes-2
“无聊猿” BAYC 的内忧与外患
The best way to learn SEO: search engine
leetcode59. 螺旋矩阵 II(中等)
Three methods of adding color to latex text
idea控制台彩色日志
CDN acceleration and cracking anti-theft chain function
TS基础篇
Due to high network costs, arbitrum Odyssey activities are suspended, and nitro release is imminent
After sharing the clone remote project, NPM install reports an error - CB () never called! This is an error with npm itself.
Huawei equipment configuration ospf-bgp linkage
3. Business and load balancing of high architecture
SSM learning