【问题标题】:The maximum in each row每行的最大值
【发布时间】:2014-11-08 09:22:44
【问题描述】:

我有一个问题要问你。我需要在每一行中写下最大元素。比如我的表:

1 2 3 4
5 6 7 8
9 10 11 12

我想得到 4,8,12 我试过但没有结果:

Program Lab2;
type A=array[1..5,1..5] of integer;
var x:A;
i,j,s,max:integer;
Begin
 writeln('Write date:');
 for i:=1 to 5 do
  for j:=1 to 5 do
    read(x[i,j]);

 for i:=1 to 5 do
  for j:=1 to 5 do
  begin
   max:=x[i,1];
    if (max<x[i,j]) then max:=x[i,j];
   writeln(max);
  end;
 readln;

请帮帮我 结束。

【问题讨论】:

  • 您的 writeln 应该在外部 for,与 max:=x[i,1] 相同

标签: pascal freepascal pascalscript delphi turbo-pascal


【解决方案1】:

只有三个小错误:

1) if (max&lt;x[i,j]) 应该在第二个 for 循环之外,因为您希望每行只初始化一次最大值。

2) writeln(max); 应该在第二个 for 循环之外,您希望每行只打印一次该值。

3) read(x[i,j]); 我推荐使用 readln (x[i,j]) 因为 read 你只能读一个字符,而 readln 你是红色字符直到你找到一个新的行字符,这样你就可以输入更多的数字超过两位数。

这仅对字符串有意义,您可以将readreadln 与整数一起使用

我还建议您在编写控制结构(for、while、if 等)的同一行中编写关键字 begin,因为这样它更类似于 C 编码风格约定,一个我猜最流行的编码风格。如果您尝试为任何语言保持类似的编码风格,也对您更好。

所以代码将是:

Program Lab2;
const SIZE=3;
type A=array [1..SIZE,1..SIZE] of integer;
var x:A;
i,j,max:integer;
Begin
  writeln('Write date:');
  for i:=1 to SIZE do begin
    for j:=1 to SIZE do begin
      readln(x[i,j]);
    end;
  end;
  for i:=1 to SIZE do begin
    max:=x[i,1];
    for j:=1 to SIZE do begin
      if (max<x[i,j]) then begin
        max:=x[i,j];
      end;
    end;
    writeln('the max value of the row ',i ,' is ',max);
end;
 readln;
 readln;
end.

【讨论】:

  • with read you only read one character - 至少对于整数来说是错误的。
  • 你说得对,很久没有用pascal编程了,对不起
猜你喜欢
  • 2019-04-12
  • 2015-01-09
  • 2016-07-28
  • 1970-01-01
  • 2015-07-31
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多