pascal 中的同时变量赋值
我希望在 Pascal 中同时进行变量赋值。
据我所知,这是不可能的。谷歌搜索这个问题,我可以看到许多编程语言都实现了这一点,但我找不到如何在 Pascal 中做到这一点。
例如,在Python中我可以这样做:
(x, y) = (y, x)
在Pascal中,我需要一个额外的变量来保存x被删除之前的值,如下所示:
bubble := x;
x := y;
y := bubble;
那么,Pascal中是否有同时赋值,或者我应该将代码重写为类似的内容上面那个泡泡?
我不仅需要进行交换;还需要进行交换。有时我必须做这样的事情:
(x,y) = (x+1,y+x)
像下面这样做可以吗?
old_x := x;
old_y := y;
x := x + 1; // maybe x := old_x + 1;
y := old_y + old_x;
I wish to do simultaneous variable assignment in Pascal.
As far as I know, it's not possible. Googling on the issue, I can see that many programming languages implement that, but I can't find how to do it in Pascal.
For example, in Python I can do this:
(x, y) = (y, x)
In Pascal, I need an additional variable to hold the value of x before it's removed, something like this:
bubble := x;
x := y;
y := bubble;
So, is there simultaneous assignment in Pascal, or should I rewrite the code to something like the bubble thing above?
I don't just have to do swaps; sometimes I have to do things like this:
(x,y) = (x+1,y+x)
Would it be ok to do it like the following?
old_x := x;
old_y := y;
x := x + 1; // maybe x := old_x + 1;
y := old_y + old_x;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我对 Pascal 一点也不熟悉,但我找不到任何特殊的
swap
函数可以满足您的要求。无论如何,你所做的都是完全合理的;
swap
的任何标准实现都需要一个临时变量来保存要交换的值之一。我在上面编写的代码中唯一要更改的是将变量重命名为 temp,以明确该变量仅出于交换目的而临时存在:编辑: 更改
x
和y
时所做的操作也没有任何问题。如果您需要保留旧值作为计算的一部分,那么将旧值分配给变量然后使用它是完全可以的。I'm not familiar at all with Pascal, but I can't find any special
swap
function that does what you want.In any case, what you're doing is perfectly reasonable; any standard implementation of
swap
requires a temporary variable to hold one of the values being swapped. The only thing I would change in the code you have written above is to rename the variable totemp
, to make it clear that the variable only exists temporarily for the purposes of the swap:EDIT: There's also nothing wrong with what you're doing when changing
x
andy
. If you need to keep the old value as part of your calculations, it's perfectly fine to assign the old value to a variable and then use it.PASCAL 不包含同时变量赋值。
它也不包含 SWAP(X,Y) 预定义过程。
你必须自己做。
您可能需要考虑购买 [Jensen &沃斯]。它仍然是该语言的最佳参考手册。如果您使用的是 Borland PASCAL 系统之一,请使用它附带的手册:Borland 进行了一些不兼容的更改,但仍然使该语言更易于使用。
PASCAL does not contain a simultaneous variable assignment.
Nor does it contain a SWAP(X,Y) predefined procedure.
You have to do it yourself.
You might want to consider buying a copy of [Jensen & Wirth]. It is still the best reference manual available on the language. If you are using one of the Borland PASCAL systems, use the manual that came with it: Borland made some incompatible changes, that nevertheless made the language significantly easier to use.