简单的伪代码问题 [英] Simple Pseudocode Code Question

查看:58
本文介绍了简单的伪代码问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对伪代码有点陌生.我明白代码在说什么,但很难把这些片段放在一起.我应该如何理解这段代码在做什么:

I'm a little new to pseudocode. I understand what the code is saying, but having a hard time putting the pieces together. How should I be thinking to understand what this code is doing:

假设 a1, a2, ..., ak 是 k 个数字的数组.下面有什么作用代码片段做什么?简要说明原因.假设所有缩进的行属于循环内.

Suppose that a1, a2, . . . , ak is an array of k numbers. What does the following code fragment do? Briefly explain why. Assume that all the indented lines belong inside the loop.

1 for p := 1 to ⌊k/2⌋
2     t := ap
3     ap := ak−p+1
4     ak−p+1 := t

推荐答案

好吧,

1 for p := 1 to ⌊k/2⌋

意味着,我们要到数组的一半.

means, we're going up to the half of the array.

2 t := ap
3 ap := ak−p+1
4 ak−p+1 := t

这种模式可以被识别为与临时t交换".什么是交换?

This pattern can be recognized as a "swap with temporary t". And what is swapped?

好吧,apak-p+1,其中一个是数组 start 中的 p-th 个元素,另一个是 p-从末尾开始的第一个.

Well, ap and ak-p+1, one being the p-th element from the array start, the other one the p-th one from the end.

总结一下:

您将第 n 的第一个与 n 的最后一个数组值交换到数组的一半.然后呢?数组颠倒了.

You swap the n-th first with the n-th last array value up to the half of the array. And afterwards? The array is reversed.

请注意,您的伪代码格式看起来很奇怪 - 而且,最重要的是 - 模棱两可.

Note that your pseudocode-format looks really weird - and, most importantly - ambiguous.

ak-p+1 等价于 a[k-p+1] 还是 a[k]-p+1还是a[kp]+1?如果不是,你是如何表达其他的.

Is ak-p+1 equivalent to a[k-p+1] or to a[k]-p+1 or a[k-p]+1? If not, how did you express the other ones.

因此,首先,我会将这段代码转换为类似于 Python 的实际源代码,这样更易​​于阅读.

So at first, I'll convert this code to an actual source like Python's, which is much easier to read.

编辑.

I) 好吧,正如您发布的那样,数组范围从 a1ak.

I) Well, as you posted, the array ranges from a1 to ak.

II) 想想如何交换两个变量(ab)的值:

II) Think how you could swap the values of two variables (a and b):

1 temp := a
2 a    := b
3 b    := temp

当然,由于您在 2 行中用 b 覆盖了 a,因此您必须存储旧的 a 临时值,即 temp.

Of course, since you overwrote a with b in line 2, you had to store the old a value in a temporary, which is temp.

这篇关于简单的伪代码问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆