VB代码:
(2018年4月浙江)17.分析数组a中各元素依次变化的情况,进行如下定义: ●变化段:数组中相邻两个元素构成一个变化段。变化段有上升段(a(i)>a(i-1))、下降段(a(i)
●波峰:从上升段到下降段形成一个波峰。波峰的起点是峰顶前所有连续上升段中的第1个,终点是峰顶后所有连续下降段中的最后1个。
●对称波峰:上升段与下降段个数相同的波峰称为对称波峰。
下图为一组数据的变化段及波峰示意图。
现要求统计数组a各元素依次变化过程中“对称波峰”的个数。小李依据上述描述设计了如下VB程序。请回答下列问题: (1)数组元素“1,4,3,3,2,6,8,7,9,3,4,7,9,6,3,1”依次变化过程中“对称波峰”的个数为。 (2)请在划线处填入合适的代码。 Const n = 16 Dim a(1 To n) As Integer Private Sub Command1_Click() Dim flag As Integer, count As Integer, steps As Integer, i As Integer flag = 0: steps = 0: count = 0 For i =① To n
If a(i) > a(i – 1) Then
If issympeak(flag, steps) Then count = count + 1
If flag = 0 Or flag = -1 Then
②
Else
steps = steps + 1
End If
flag = 1
ElseIf a(i) = a(i – 1) Then
If issympeak(flag, steps) Then count = count + 1
steps = 0
flag = 0
Else
steps = steps – 1
flag = -1
End If Next i If issympeak(flag, steps) Then count = count + 1
Text1.Text = Str(count) End Sub Function issympeak(flag As Integer, steps As Integer) As Boolean
If③ Then issympeak = True Else issympeak = False End Function Private Sub FormLoad() ‘读取数据,并存储到数组a中。代码略 End Sub参考答案:(1)3 (2) ①2 ②steps = 1 ③flag = -1 And steps = 0 或其他等价表达式
def issympeak(flag,steps):
if flag==-1 and steps==0:
return True
return False a=[1,4,3,3,2,6,8,7,9,3,4,7,9,6,3,1] n=len(a) print(a) flag=0 steps=0 count=0 for i in range(1,n):
if a[i]>a[i-1]:
if issympeak(flag,steps):
count=count+1
if flag==0 or flag==-1:
steps=1
else:
steps=steps+1
flag=1
elif a[i]==a[i-1]:
if issympeak(flag,steps):
count=count+1
steps=0
flage=0
else:
steps=steps-1
flag=-1 if issympeak(flag,steps):
count=count+1 print(‘对称波峰的个数为:’,count)
Python代码运行结果: