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

pascal高手请进。猜数字guess.pas
味味最近在玩猜数字的游戏,现在她也希望你来玩一下这个游戏。猜数字游戏的规则是这样的,告诉你一个正整数n(2
aa的小女巫2008 1年前 已收到1个回答 举报

caicainiu 幼苗

共回答了13个问题采纳率:92.3% 举报

下面代码需要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

1年前 追问

6

aa的小女巫2008 举报

还有没有一点简单的方法?谢谢。
最好附上讲解。

举报 caicainiu

① 这个方法已是很简洁的了,那两个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。

⑥ 修正上面输出一个错误(张贴时错位了)

2

90

09

⑦ 不明白再追问~

可能相似的问题
Copyright © 2024 YULUCN.COM - 雨露学习互助 - 17 q. 0.608 s. - webmaster@yulucn.com