我试图在MetaPost宏中连接一些字符串,其中一些字符串来自数值参数。但是,我收到一条错误消息“额外的令牌将被刷新”。
问题的实质在于下面的片段:
def foo(expr a) =
show a; % this prints 1
show str a; % this prints "" and crashes
enddef;
show str 1; % this prints "1"
foo(1);用str将数字更改为字符串在宏之外工作,但在宏中不起作用。为什么?
发布于 2021-05-08 17:36:13
‘`str’返回后缀的字符串表示形式,而不是数字值。1是后缀。
str 1是有效的("1"),因为1是一个suffix.str -1,因为没有后缀-1是无效的。
但是等待…[1]和[-1]都是后缀,str[1]呈现"1" (是的,没有[]),str[-1]是[-1]
将整数或浮点数转换为字符串的正确函数是decimal。
用decimal重新实现str是可能的,只是为了好玩:
% Integer to string without decimal
vardef funny_decimal(expr num) =
save s; string s; s=str[num]; % [] needed to evaluate num
if substring(0,1) of s = "[":
substring (1,length(s)-1) of s
else:
s
fi
enddef;https://stackoverflow.com/questions/65054626
复制相似问题