帕斯卡:范围内的数字总和



有多少个小于 1000 的正整数的数字之和等于 6?

不知道如何使用Pascal开始此操作。在Python上,我的脚本看起来像这样:

a = 1
b = 1000
for i in range(a,b):
........

我不知道如何访问数字。如果有人能给我一个提示,我应该能够从这里取得一些进展。

你的问题基本上只是"如何在 Pascal 中完成一个 for 循环"......只需检查文档,例如:http://pascal-programming.info/lesson4.php#JUMP3

我也闻到了作业的味道。 ;)

忽略对Pascal的讽刺评论(它仍然是一种可行的语言,并且存在于Delphi的核心;它的语法已被借用到几种"现代"语言中),这个问题实际上比人们想象的要复杂得多。首先,我将展示程序,然后我将进行解释。

var
 i, j, found, total: integer;
 s: string;
begin
 found:= 0;  // how many numbers whose digits add up to six
 for i:= 1 to 1000 do
  begin
   s:= inttostr (i);
   total:= 0;
   for j:= 1 to length (s) do
    total:= total + ord (s[j]) - ord ('0');
   if total = 6 then found:= found + 1;
  end;
 writeln ('I found ', found, ' numbers whose digits add up to six');
 readln
end.

关键是将索引号(i)转换为字符串(即"inttostr(i)"行),然后迭代字符串的数字并将它们相加。

这是解决方案,无需不必要地转换为字符串。它的工作原理是获取最右边的数字,将其值添加到累加器Total,然后通过执行整数除以 10 来删除最右边的数字,然后重复该过程,直到我们什么都没有了。

var
  Value, Digit, Total, NumValues: Integer;
  i: Integer;
begin
  NumValues := 0;
  for i := 1 to 1000 do
  begin
    Value := i;
    Total := 0;
    repeat
      Digit := Value mod 10;
      Total := Total + Digit;
      Value := Value div 10;
    until Value = 0;
    if Total = 6 then
      Inc(NumValues);
  end;
  WriteLn ('I found ', NumValues, ' numbers whose digits add up to six');
  ReadLn;
end.

最新更新