作业帮 > 综合 > 作业

pascal高手请进。猜数字guess.pas

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/07/15 02:16:23
pascal高手请进。猜数字guess.pas
味味最近在玩猜数字的游戏,现在她也希望你来玩一下这个游戏。猜数字游戏的规则是这样的,告诉你一个正整数n(2
下面代码需要uses math,sysutils; -- 如果有规定不让用,可以再编写两个函数;如果不需要输入保护,可以修改。program number_guess;
uses math, sysutils;
    function factorial(const n : Integer) : Int64;
    var
        i : Integer;
    begin
        if n = 0 then exit(1);
        factorial := 1;
        for i := 2 to n do 
            factorial *= i;

    end;
var
    sum, s, sum_of_fact, r_min, r_max : Int64;
    i, j, n, num, errcode : Integer;    
    res, instr : String;
begin
    repeat
        readln(instr);
        val(instr, n, errcode);
        if (errcode = 0) and (n in [2..11]) then break;
        writeln('Invalid number, try again.');
    until 1=0;
    repeat
        readln(instr);
        val(instr, s, errcode);
        if (errcode = 0) and (s > 0) then break;
        writeln('Invalud number, try again.');
    until 1=0;
    res := 'not found';
    r_min := 1;
    r_max := trunc(power(10,n))-1;
    for i := r_min to r_max do 
    begin
        sum := 0; num := i;
        while (num > 0) do begin sum += num mod 10; num := num div 10;end;
        sum *= factorial(n-1);
        sum_of_fact := 0;
        for j := 0 to n-1 do sum_of_fact += sum * trunc(power(10,j));
        if sum_of_fact - i = s then 
        begin 
            res := Format('%.*d',[n,i]);            
            break;
        end;
    end;
    writeln(res);
end.运行:3
1209
123
-------
4
45440
1222
-------
2
90
90
------
2
100
not found
------
1
Invalid number, try again.
2
-10
Invalud number, try again.
91
19
再问: 还有没有一点简单的方法?谢谢。
最好附上讲解。
再答: ① 这个方法已是很简洁的了,那两个repeat..until 只是为了验证用户,如果你需要,可以直接:readln(n);
readln(s);就能省不少代码。② 原理很简单。给定任意一个n位数,比如:4位数,1234. 先分拆位数求和: sum := 1+2+3+4 = 10; 然后把这和sum * (4-1)! - 1234, 这就是题目中的判断标准,如何这个值=s,那么符合要求了。③ 函数factorial是为了求阶乘(注意调用时,n-1)④ r_max 是根据n值,求上限;r_min = 1(因为像输入的90,是可以有09这个值,意味着循环总是总个位数开始的)⑤ res := Format('%.*d',[n,i])这句只是为了把9填充成09。⑥ 修正上面输出一个错误(张贴时错位了)29009⑦ 不明白再追问~