在 Commodore 64 BASIC 中选择随机字符串
我的程序中有这样的变量声明:
X="MAGENTA"
Y="CYAN"
Z="TAN"
A="KHAKI"
现在我想要的是随机选择其中一个并打印它。但如何做到这一点呢?
I have this variable declarations on my program:
X="MAGENTA"
Y="CYAN"
Z="TAN"
A="KHAKI"
Now what I want is to randomly choose one of these and PRINT
it. But how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的 BASIC 很生疏,但你应该能够使用类似的东西:
或者,将其放入子例程中以进行代码重用:
当然,你可能应该使用数组来完成这类事情,这样你就可以使用:
My BASIC is pretty rusty but you should just be able to use something like:
or, putting it in a subroutine for code re-use:
Of course, you probably should be using arrays for that sort of thing so you can just use:
上述答案是正确且全面的。
另一方面,这个答案不是,但我上个月实际上做了一点 Commodore BASIC,并认为字符串索引有时会很有用,所以这里有一个非答案,可以重新构建您的问题。
<代码>
100 X$ =“洋红色卡其色”
第110章 打印中$(X$,INT(RND(1)*4)*7, 7)
此代码获取从 0 到 3 的随机整数,然后使用它来查找包含所有四个条目的单个字符串的起始索引,每个条目都被填充(如有必要)为 7 个字符。需要该填充是因为 MID$ 的最后一个参数是要提取的子字符串的长度。
为什么要麻烦?
何时考虑对数组建立索引:
<代码>
(1) 当您的字符串数据的长度接近均匀时,并且
(2) 当你有很多小弦时。
如果这两个条件为真,则包括数据在内的完整代码会更加紧凑,并且由于分配的指针较少而占用较少的内存。
PS 如果您发现我犯了一个相差一的错误,请加分!
The above answer is correct and comprehensive.
This answer, on the other hand, is not, but I was actually doing a little bit of Commodore BASIC last month and decided that string indexing CAN be useful, sometimes, so here's a non-answer that sort of reframes your problem.
100 X$ = "MAGENTACYAN TAN KHAKI "
110 PRINT MID$(X$,INT(RND(1)*4)*7, 7)
This code gets a random int from 0 to 3, then uses that to find the start index into a single string that contains all four entries, each of which is padded out (where necessary) to 7 characters. That padding is needed because the final parameter to MID$ is the length of the substring to be extracted.
WHY BOTHER?
When to consider indexing over an array:
(1) when your string data is near-uniform length, and
(2) when you have a LOT of little strings.
If those two conditions are true, then the full code, including the data, is more compact, and takes less memory due to allocating fewer pointers.
P.S. Bonus point if you find that I've made an off-by-one error!
这是另一种方法,使用一个变量作为输出,并使用 ON..GOSUB 根据 [1..4] 范围内的随机数来设置它。
Here's another way to do it, using one variable for the output and ON..GOSUB to set it based on a random number in the range [1..4].