2012-12-25 30 views
0

一个字符串,这里是我的代码:扭转了我想用递归函数反转字符串中的递归的方式

Program InvertTheString; 
var n:integer;word:string; 

Function Invert (N:integer; word:string) : string; 
begin 
    if N=1 then 
     Invert:=word[N]+Invert 
    Else 
     Invert:=Invert(N-1,word); 
end; 

BEGIN 
readln(word); 
n:=length(word); 
writeln (Invert(N,word)); 

writeln;write('Press Enter To Exit...'); 
readln; 
END. 

但它不工作,哪里是拨错?

+1

是否编译? – rene

+0

是的,编译,但输出是如此可怕! – Nofuzy

+2

输出结果如何?也许将其添加到您的问题... – rene

回答

3
Function Invert (N:integer; word:string) : string; 
begin 
    if N=0 then 
     Invert:='' 
    Else 
     Invert:= word[N] + Invert(N-1,word); 
end; 
+0

不错和接受,谢谢你非常rene。 – Nofuzy

+1

自1990年以来,我还没有完成pascal ... – rene

+0

您有一个伟大的编程思想;) – Nofuzy

2

我不做帕斯卡,但是典型的(简单)递归相反,在伪代码,看起来像:

function reverse(word) 
    if empty(word) return "" 
    else return reverse(withoutFirstLetter(word)) + firstLetterOf(word) 
+0

但是我需要pascal一个,我真的可以为C++编写它,但是在pascal中有一些区别.. – Nofuzy

0
Function Invert (ch:string) : string; 
begin 
if ch='' then 
Invert:='' 
else 
{get the last letter of the string + eliminate it and execute the function} 
Invert:=copy(ch,length(ch),1)+Invert(copy(ch,1,length(ch)-1)); 
end; 
+0

您的格式似乎不正确 - 用四个空格缩进行以将它们格式化为代码。另外,你能解释你的代码吗? –

+0

如果你有pascal编译器,你可以试试它。这个想法只是用一个参数递归地反转一个字符串。这个功能的复杂性仍然比另一个更大,所以它不是一个解决方案,而仅仅是为了apparenc –