Friday, January 7

A programming problem.

A program:


     ...

again:n=a();
if (n>0) {
n=b;
goto again;
}
...


You know, goto is not a good style in programming. How to get rid of "goto" in this code?
try:
// wrong program.

do{
n=a();
}while(n>0);


Where is "n=b"?

Need Help!


Damon gave a neat solution:

n=a();
while(n>0){
n=b;
n=a();
}
It's very beautiful.

Now my question changed to:
...
again:n=a();
if (n>0) {
n=b;
goto again;
}
else{
n=c();
}
...
???

Labels:

2 Comments:

At January 09, 2005 1:19 AM, Anonymous Anonymous said...

again:n=a();
if (n>0) {
n=b;
goto again;
}
else{
n=c();
}

我不太看得懂这段程序是什么意思,就我看来,直接改成这样:

n=c();

因为当a()返回值总大于0时,这是一个死循环。只有在a()返回值小于等于0时,n=c()。

其实前面的程序就有问题:

n=a();
while(n>0){
n=b;
n=a();
}

这一段程序执行完毕之后,n无论如何不可能为b,看不出有何意义。

 
At January 10, 2005 10:16 AM, Blogger Unknown said...

Actually, "n=a()", "n=b", "n=c()" only mean "Command 1", "Command 2", "Command 3" in the post. I'm thinking of the 流程 of the program, not the detail command.

The last code can be changed as:

n=a();
while(n>0){
n=b;
n=a();
}
n=c();
----------------------
As I said, it means:
...
Command 1;
while (n>0){
Command 2;
Command 1;
}
Command 3;
...

 

<< Home