c++ - 使用链表添加两个数字

标签 c++

我正在尝试将两个由链表表示的数字相加。所以我插入了数字 3->2->8 和 6->5->4。我试图获取数字 328 和 654,然后将两者相加并将它们插入到第三个列表中。我在计算数字时遇到了一些问题。这是代码。

    #include<bits/stdc++.h>

using namespace std;


struct Node{
int data;
struct Node *next;
};
int flag=1;
void input(Node **head,int num)
{
    Node *temp=(struct Node*)malloc(sizeof(struct Node));
    temp->data=num;
    if(!flag)temp->next=*head;
    if(flag){temp->next=NULL;flag=0;}
    *head=temp;
}

void add(Node *l1,Node *l2,Node *l3)
{
    Node *cur1=l1;
    Node *cur2=l2;
    int size1=0,size2=0;

    while(cur1!=NULL)
    {
       size1++;

        cur1=cur1->next;
    }
    while(cur2!=NULL)
    {
        size2++;
        cur2=cur2->next;
    }
    int i=size1-1,j=size2-1,sum1=0,sum2=0;
    cur1=l1;cur2=l2;
    cout<<i<<endl;
    while(cur1!=NULL)
    {
        cout<<cur1->data<<"\t";
        cout<<cur1->data*pow(10,i)<<"\t";

        sum1=sum1+cur1->data*pow(10,i);
        cout<<sum1<<endl;
        i--;
        cur1=cur1->next;
    }
    cout<<sum1<<endl;
    while(cur2!=NULL)
    {    cout<<cur2->data<<"\t";
        cout<<cur2->data*pow(10,j)<<"\t";
        sum2=sum2+cur2->data*pow(10,j);
        cout<<sum2<<endl;
        j--;
        cur2=cur2->next;
    }
    cout<<sum2<<endl;
    sum1+=sum2;
    while(sum1!=0)
    {
        int r=sum1%10;
        input(&l3,r);
        sum1/=10;
    }
    cur1=l3;
    while(cur1!=NULL)
    {
        cout<<cur1->data;
        cur1=cur1->next;
    }
}

int main()
{
    Node *l1=NULL;
    Node *l2=NULL;
    Node *l3=NULL;
    input(&l1,8);
    input(&l1,2);
    input(&l1,3);
    flag=1;
    input(&l2,4);
    input(&l2,5);
    input(&l2,6);
    add(l1,l2,l3);
    return 0;
}

我得到输出

2 //value of i
3       300     299 //cur1->data*pow(10,i) is initially 300 then becomes 299
2       20      319
8       8       327
327 //total sum which should be 328
6       600     599 //Same problem 
5       50      649
4       4       653
653 //total sum which should be 654
980 //sum of 327 and 653 

最佳答案

问题可能是由于截断引起的。 pow 函数返回 float 。然后将其转换为整数,这会导致截断。

例子:

299.99999999 as float will become 299 as int

尝试先加 0.5 来取整。

喜欢:

sum1=sum1+(cur1->data*pow(10,i) + 0.5);

正如@viraptor 评论的那样,最好避免 float (即 pow)。尝试类似的东西:

sum1 = 0;
while(cur1 != NULL)
{
    sum1 = 10 * sum1;
    sum1 = sum1 + cur1->data;
    cur1=cur1->next;
}

那么所有的计算都是在整数上完成的,你不会因为 float 和 int 之间的转换而遇到问题。

关于c++ - 使用链表添加两个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36369097/

相关文章:

c++ - 请求想法 - 如何对具有多行和 3 列的二维数组进行排序,维护数据行

c++ - g++ 签名/符号 : no difference between static and non-static member function?

c++ - 尝试使用 SFINAE 实现类型检查时出错

c++ - Cocos2d-x 中的 CCCallFunc 及其子类

c++ - 是否可以在不继承任何 Qt 对象的情况下使用 Qt 线程?

c++ - 如何让 PCRE 与 Code::blocks 一起正常工作?

c++ - 如何确保 `waitpid(-1, &stat, WNOHANG)` 收集所有子进程

c++ - 在 C++ 中检查数组的顺序

c++ - 如何追查内存泄漏 valgrind 说不存在?

c# - Shell_NotifyIconA/Shell_NotifyIconW...有什么区别?