我正在C中使用單個鏈表計算器(是的,它是作業)。我有添加功能「工作」,但由於某種原因,我只能添加兩個相同長度的值。我真的不知道如何添加像12 + 128.目前我的代碼只接受120 + 128.我做錯了什麼,我該如何解決這個代碼?在鏈接列表計算器中添加值
struct digit* add(struct digit *x, struct digit *y)
{
int carry = 0;
struct digit *xHead;
struct digit *yHead;
struct digit *totalHead;
struct digit *current_Digit;
xHead = x;
yHead = y;
totalHead = NULL;
while(x != NULL && y != NULL)
{
current_Digit = (struct digit *)malloc(sizeof(struct digit));
current_Digit->value = x->value + y->value + carry;
//calculates the carry
carry = 0;
if(current_Digit->value > 9)
{
carry = 1;
current_Digit->value = current_Digit->value % 10;
}
else
{
carry = 0;
}
current_Digit->next = totalHead;
totalHead = current_Digit;
x = x->next;
y = y->next;
}
return totalHead;
}
你的struct digit看起來像什麼? – BlackBear 2011-04-13 18:04:58
結構數字 { int value; // data struct digit * next; //下一個指針 }; – user706553 2011-04-13 18:06:30