栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C语言解题—— 整数a+b(大数运算)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C语言解题—— 整数a+b(大数运算)

C语言解题

每天更新一道OJ题目,今日介绍简单整数和大数加法的使用方法和示例。


前言

I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.

这里使用多种解法来对其进行编译。


一、输入

示例:The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.

二、输出

For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.


代码
1、示例:
#include 
#include 
int main()
{
    long a,b,sum;
    scanf("%ld%ldn",&a,&b);
    sum = a + b;
    printf("%ldn",sum);
    return 0;
}


2、示例:超长(超100位)加法运算

#include 
#include 
#define  N 10000

int main()
{
    char num1[N] = {0},num2[N] = {0},result[N]={0};
    long len_1,len_2,len;
    int i;
    scanf("%s %s",num1,num2);
    
    len_1 = strlen(num1);
    len_2 = strlen(num2);
    len = (len_1>len_2) ? len_1:len_2;
    len++;
    
    for(i = 0 ;ilen_2)
    {
        for(;i0;i--)
	{
		if(result[i]>=10)
		{
			result[i] = result[i]%10;
			result[i-1]++;
		}
	 }
	 
	 //判断是后位数多出一位 9+8=17变成2位数,如果没有则全部前移。并变回数字的ASC2码 
	 if(result[0]!= 0)
	 {
	 	for(i = 0;i
int main()
{
    int a,b;
	while(scanf("%d %d",&a,&b)==2)
	{
       printf("%dn",a+b);
	}
    return 0;
}

以上就是今天的内容,本文仅仅简单介绍了加法如何运算使用。

大数运算的核心就是:模拟,模拟我们日常用纸笔算数字的加减乘除流程,然后再根据计算机、编程语言等特性适当存储计算即可,不过,大数除法运算稍微特殊一点,和我们直接模拟的思维方式稍有不同。

大数加法是最简单的,简单模拟即可。首先,我们想一下两个数加法的流程:从右向左计算求和、进位,一直到最后。

在编程语言中同样也是模拟从右向左逐位相加的过程,不过在具体实现上需要注意一些细节。

  • 枚举字符串将其转换程char[]提高效率
  • 从右往左进行计算,可以将结果放到一个数组中最后组成字符串,也可以使用StringBuider拼接,拼接的时候最后要逆置一下顺序。
  • 余数每次叠加过需要清零,两数相加如果大于等于10即有余数,添加到结果中该位置的数也应该是该数%10的结果。
  • 计算完最后还要看看余数是否为1,如果为1需要将其添加到结果,例如 "991"+"11"算三个位置为002但还有一个余数需要添加,所以应该是1002。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1010217.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号