Pascal字符串用法(正确的Python示例)
我有一个任务,需要用户输入一个11位的代码(字符串)。
1) 比如说,用户输入的代码是37605030299。
2) 然后我需要检查最后一个数字是否匹配。获取最后一个数字的方法是: nr11 = (nr1*1 + nr2*2 + nr3*3 + nr4*4 + nr5*5 + nr6*6 + nr7*7 + nr8*8 + nr9*9 + nr10*1) mod 11
3) 这是我写的代码:
var C, nr1, nr2, nr3, nr4, nr5, nr6, nr7, nr8, nr9, nr10, nr11: string;
begin
nr1:=(copy(C, 1, 1));
nr2:=(copy(C, 2, 1));
nr3:=(copy(C, 3, 1));
nr4:=(copy(C, 4, 1));
nr5:=(copy(C, 5, 1));
nr6:=(copy(C, 6, 1));
nr7:=(copy(C, 7, 1));
nr8:=(copy(C, 8, 1));
nr9:=(copy(C, 9, 1));
nr10:=(copy(C, 10, 1));
nr11:=(copy(C, 11, 1));
writeln('Enter the code which contains 11 digits:');
readln(C);
if nr11 = (nr1*1 + nr2*2 + nr3*3 + nr4*4 + nr5*5 + nr6*6 + nr7*7 + nr8*8 + nr9*9 + nr10*1) mod 11 then
begin
writeln('The code is correct!');
end
else
if nr11 <> (nr1*1 + nr2*2 + nr3*3 + nr4*4 + nr5*5 + nr6*6 + nr7*7 + nr8*8 + nr9*9 + nr10*1) mod 11
begin
writeln('The code is incorrect!');
end;
readln();
end.
这个代码不工作,因为我知道在公式中不能像我这样使用字符串,但这样做会有效吗?我正在学习Pascal,如果这看起来太傻,请见谅。
这个用户界面的代码应该是正确的。检查一下:
1*3 + 2*7 + 3*6 + 4*0 + 5*5 + 6*0 + 7*3 + 8*0 + 9*2 + 1*9 = 108
108/11 ~ 9.8
9*11 = 99
108-99 = 9(答案是9,所以最后一位数字必须是9,最后一位是9,这表明代码是正确的)
如果你不明白我想做什么,我找到了一个在Python中应该是正确的例子:
def checkIDCode(code):
if len(code) != 11 or not code.isdigit():
return False
c = map(int,code)
w1 = [1,2,3,4,5,6,7,8,9,1]
w2 = [3,4,5,6,7,8,9,1,2,3]
s1 = sum(map(lambda x,y: x*y, c[:-1], w1))%11
s2 = (sum(map(lambda x,y: x*y, c[:-1], w2))%11)%10
return s1 == c[-1] or s1 == 10 and s2 == c[-1]
2 个回答
这看起来像是ISBN(国际标准书号)。为了计算校验位,我建议使用以下方法。
function DigitToInt(const c: Char): Integer;
begin
if (c<'0') or (c>'9') then
raise Exception.Create('Invalid input');
Result := ord(c)-ord('0');
end;
这个代码将字符'0'到'9'之间的单个字符转换成对应的整数值。
function CheckDigit(const s: string): Integer;
var
i: Integer;
begin
if Length(s)<>11 then
raise Exception.Create('Invalid input');
Result := 0;
for i := 1 to 10 do
inc(Result, DigitToInt(s[i])*i);
Result := Result mod 11;
end;
这个代码用来计算一个11位代码的校验位。
要比较实际的校验位和计算出来的校验位,你可以写:
if CheckDigit(code) <> DigitToInt(code[11]) then
.... handle error
首先,你需要在C为空的时候复制内容。你应该在尝试访问它的元素之前先执行readln(C):
writeln('Enter the code which contains 11 digits:');
readln(C);
nr1:=...
nr2:=...
第二,如果值只有一个字符,你可以通过索引来访问它:
nr1:= C[1];
nr2:= C[2];
...
要把字符串转换成整数,你需要引入sysutils这个库,才能使用StrToInt函数:http://www.freepascal.org/docs-html/rtl/sysutils/strtoint.html
另一种方法(逐个字符)是计算字符值与48之间的差(48是字符'0'的ASCII码)
示例代码:
uses sysutils;
var C:string
nr1, nr2, nr3, nr4, nr5, nr6, nr7, nr8, nr9, nr10, nr11: integer;
begin
readln(C);
nr1:=strtoint(C[1]);
nr2:=strtoint(C[2]);
nr3:=strtoint(C[3]);
.
.
.
if nr11 = (nr1*1 + nr2*2 + nr3*3 + nr4*4 + nr5*5 + nr6*6 + nr7*7 + nr8*8 + nr9*9 + nr10*1) mod 11 then
writeln('The code is correct!')
//if you skip the begin/end statements, only the next statement
//is executed in loops/if statements
else writeln('Not correct'); //notice that I didn't use ELSE IF but ELSE
readln;
//in Pascal you can skip the parathenses if you don't pass arguments to the function
end.