能有人請幫我解決這個問題,在MATLAB:Matlab函數huge_add?
寫函數調用
huge_add
,增加了在一起的兩個指定爲使用十進制形式的字符串任意長度的正整數。單輸出參數是結果,它也是一個字符串。輸入和輸出只能包含數字;不允許使用逗號,空格或其他字符。如果這些假設中的任何一個被輸入違反,則該函數返回數字-1
。
這是我寫的代碼是:
function[c]=huge_add(a1,b1)
aaa=length(a1);
bbb=length(b1);
c=0;
if isnumeric(a1) ||isnumeric(b1)
c=-1;
else if ~isnumeric(a1) ||~isnumeric(b1)
for i=1:aaa
if a1(i)~='1'&& a1(i)~='2'&&a1(i)~='3'&&a1(i)~='4'&&a1(i)~='5'&&a1(i)~='6'&&a1(i)~='7'&&a1(i)~='8'&&a1(i)~='9'&&a1(i)~='0'
c=-1;
end
end
for i=1:bbb
if b1(i)~='1'&&b1(i)~='2'&&b1(i)~='3'&&b1(i)~='4'&&b1(i)~='5'&&b1(i)~='6'&&b1(i)~='7'&&b1(i)~='8'&&b1(i)~='9'&&b1(i)~='0'
c=-1;
end
end
end
a=a1;
b=b1;
aa=length(a);
bb=length(b);
as=(str2num(a));
bs=(str2num(b));
af=fliplr(a);
bf=fliplr(b);
if c~=-1
if aa<bb
for ii=1:aa
x(ii)=af(ii);
y(ii)=bf(ii);
z(ii)=str2num(x(ii))+str2num(y(ii));
zz{ii}=num2str(z(ii));
end
cl=fliplr(z);
rem=(b(1):b(bb-aa));
ca=[rem,cl(1):cl(end)];
else if aa>bb
for ii=1:bb
x(ii)=af(ii);
y(ii)=bf(ii);
z(ii)=str2num(x(ii))+str2num(y(ii));
zz(ii)=num2str(z(ii))
end
cl=fliplr(z);
rem=(a(1):a(aa-bb));
ca=[rem,cl(1):cl(end)];
else
for ii=1:aa
x(ii)=af(ii);
y(ii)=bf(ii);
z(ii)=str2num(x(ii))+str2num(y(ii));
zz(ii)=num2str(z(ii));
end
cl=fliplr(z);
rem=[];
ca=[rem,cl(1):cl(end)];
end
end
d=str2num([rem,fliplr(zz)])
%d=([rem,fliplr(zz)])
c=num2str(d);
end
end
end
而我得到的錯誤是
Feedback: Your function performed correctly for argument(s) '1', '1'
Feedback: Your function performed correctly for argument(s) '10', '22'
Feedback: Your function performed correctly for argument(s) '1234', '1'
Feedback: Your function performed correctly for argument(s) '0', '0'
Feedback: Your function performed correctly for argument(s) '12', '-2'
Feedback: Your function performed correctly for argument(s) '99.99', '0'
Feedback: Your function performed correctly for argument(s) '1,234', '1'
Feedback: Your function performed correctly for argument(s) 12, 34
Feedback: Your function performed correctly for argument(s) [1 2 3], '1'
Feedback: Your function performed correctly for argument(s) '2', [50 51 52]
Feedback: Your program made an error for argument(s) '612455618766556780', '6285757'
Your solution is _not_ correct.
請幫助.....
我不明白爲什麼這需要65行循環。你不能使用['+'](http://www.mathworks.com/help/matlab/ref/plus.html)和['sprintf'](http://www.mathworks.com/help/matlab /ref/sprintf.html)? – excaza
謝謝你的幫助。我不確定如何將它們合併到代碼中。編程新手,仍然試圖更好,更好地理解它。你能指導我嗎? – ishika
我已經鏈接了充滿示例的文檔。 – excaza