c晨光


私信TA

用户名:H1320312

访问量:13130

签 名:

大佬们带带我,学渣+oo,哎,我好笨,我为什么这么笨

等  级
排  名 647
经  验 3907
参赛次数 0
文章发表 23
年  龄 10
在职情况 学生
学  校 HBWLXY
专  业 学生

  自我简介:

生活当然需要多姿多彩,不过哪有刷题精彩呢,哇咔咔

解题思路:

依次从后往前提取每个数,字符型转成int型后,然后进行加法运算

定义两个字符串,用于存储输入的两个
注意事项:
字符串中单个字符的提取

a[0]可能是大于10的数,注意进位问题



temp就是用来给a[0]进位的,数组中存的数是小于10的数



flag是用来在计算的过程中进位的



for循环中的限制应该是长的那个字符串来限制,因为短的用完了,长的可能还会继续进位(如9999和1)



string型转int型可以用强转,也可以直接减去‘0’,我下面的用的是方法2
参考代码:

#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
string st1,st2,temp0;
cin>>st1>>st2;
int length1=st1.size();
int length2=st2.size();
if(length1<length2){
temp0=st1;
st1=st2;
st2=temp0;
}
int min=(length1<length2)? length1:length2;
int max=length1+length2-min;
int a[max],flag=0,temp=0;
//int max=length1+length2-min;
for(int i=max-1;i>=0;i--){
min--;
if(min>=0)
a[i]=st1[i]-'0'+st2[min]-'0'+flag;
else
a[i]=st1[i]-'0'+flag;
flag=0;
temp=a[0]/10;//用于补齐数组的最高位 
if(a[i]>9)//用于中间位的进位 
{
a[i]=a[i]%10;
flag=1;
}
}
if(temp!=0)
cout<<temp;
for(int i=0;i<max;i++)
cout<<a[i]; 
return 0;
}

   


记得点赞哦,欢迎改良和提建议,谢谢



 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区

建议代码规范,添加注释
2018-12-13 16:39:18
  • «
  • 1
  • »