for循环中的值循环 - Maple

时间:2015-12-01 23:55:16

标签: loops for-loop maple

我正在尝试编写代码以给出输出3,-3,3然后结束该过程。理想情况下,我试图获得一些东西,如果A获取它在前一个循环中已经具有的值,则会识别并且打印此事实。 任何帮助将不胜感激,谢谢。

optimality:=proc()

global A,B
local i;
A:=3
for i from 1 to 10 do

A*(-1):=B;
A:=B;
print(A);
end do:
end proc:

2 个答案:

答案 0 :(得分:0)

如果您只想输出3, -3, 3,那么您可以使用seq

seq(3*(-1)^(i-1),i = 1..10);

打印值

print(seq(3*(-1)^(i-1),i = 1..10));

但请注意,在打印时,您无法将它们分配给变量。

通过更改i = 1..N的索引,可以将上述内容推广到您需要的任何数量。

现在,如果您的目标是了解并使用程序,上述内容并没有多大帮助。

请注意,在do - 循环中,它会设置A:=B,因此B是多余的;只需替换两行代码

A*(-1):=B;
A:=B;

A:=A*(-1);

另请注意,您无法在变量赋值的左侧执行操作 - 至少*(-1)应位于右侧。

您的代码可能看起来像

optimality:=proc()
    global A;
    local i;
A:=3;
for i from 1 to 10 do
    A:=A*(-1);
    print(A);
end do:
end proc:

答案 1 :(得分:0)

根据需要自定义......

restart;

randomize():

cycl := proc( A, input, f, {bail::truefalse:=true} )
  local i,B,T;
  B:=input;
  A[B]:=1;
  T[1]:=B;
  for i from 2 to 10 do
    B:=f(B);
    if assigned(A[B]) then
      printf("revisited value found: %a\n",[seq(j=T[j],j=A[B]..i-1),i=B]);
      if bail then
        #return seq(j=T[j],j=A[B]..i-1),i=B;
        return seq(T[j],j=A[B]..i-1),B;
      else
        A[B]:=i;
        T[i]:=B;
        # Or perhaps you just wanted to break the loop here.
      end if;
    else
      A[B]:=i;
      T[i]:=B;
    end if;
  end do;
  convert(T,list); # all the values generated
end proc:

A := 'A':
cycl( A, 3, (x->-x) );

  revisited value found: [1 = 3, 2 = -3, 3 = 3]

                              3, -3, 3

eval( A ); # last position for each distinct value

                       TABLE([-3 = 2, 3 = 1])

A := 'A':
cycl( A, 3, (x->-x), bail=false );

  revisited value found: [1 = 3, 2 = -3, 3 = 3]
  revisited value found: [2 = -3, 3 = 3, 4 = -3]
  revisited value found: [3 = 3, 4 = -3, 5 = 3]
  revisited value found: [4 = -3, 5 = 3, 6 = -3]
  revisited value found: [5 = 3, 6 = -3, 7 = 3]
  revisited value found: [6 = -3, 7 = 3, 8 = -3]
  revisited value found: [7 = 3, 8 = -3, 9 = 3]
  revisited value found: [8 = -3, 9 = 3, 10 = -3]

                 [3, -3, 3, -3, 3, -3, 3, -3, 3, -3]

eval(A); # last position for each distinct value

                       TABLE([-3 = 10, 3 = 9])

A := 'A':
cycl( A, 3, rand(7) );

  revisited value found: [2 = 5, 3 = 4, 4 = 1, 5 = 2, 6 = 5]

                            5, 4, 1, 2, 5

eval( A ); # last position for each distinct value

             TABLE([1 = 4, 2 = 5, 3 = 1, 4 = 3, 5 = 2])

A := 'A':
cycl( A, 3, rand(7), bail=false );

  revisited value found: [1 = 3, 2 = 3]
  revisited value found: [4 = 0, 5 = 0]
  revisited value found: [2 = 3, 3 = 5, 4 = 0, 5 = 0, 6 = 2, 7 = 6, 8 = 3]
  revisited value found: [6 = 2, 7 = 6, 8 = 3, 9 = 2]
  revisited value found: [9 = 2, 10 = 2]

                   [3, 3, 5, 0, 0, 2, 6, 3, 2, 2]

  eval( A ); # last position for each distinct value

             TABLE([0 = 5, 2 = 10, 3 = 8, 5 = 3, 6 = 7])