编写一个程序,生成20个1-100之间的随机整数并存入一个一维数组,求出其中的最大元素与最小元素及其序号。

如题所述

Option Explicit

Option Base 1

Private Sub Command1_Click()

Dim a(20) As Integer, i As Integer, st As String

Dim max As Integer, min As Integer, maxp As Integer, minp As Integer

For i = 1 To 20

a(i) = Int(100 * Rnd) + 1

st = st & Str(a(i))

If i Mod 10 = 0 Then st = st & vbCrLf

Next i

Text1 = st

max = a(1): min = a(1)

maxp = 1: minp = 1

For i = 2 To 20

If a(i) > max Then

max = a(i)

maxp = i

ElseIf a(i) < min Then

min = a(i)

minp = i

End If

Next i

Text2 = Val(max) & "位置是" & Val(maxp)

Text3 = Val(min) & "位置是" & Val(minp)

End Sub

Private Sub Command2_Click()

Text1 = "": Text2 = "": Text3 = ""

End Sub

Private Sub Command3_Click()

End

End Sub
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-10-20
<html>
<head>
<title>javascript</title>
<script language="javascript">

function randNumArr(count) {
var arr = [];
var f = true;
for ( var i = 0; i < count; i++) {
var r = Math.ceil(Math.random() * 99 + 1);

f = true;
for ( var j = 0; j < arr.length; j++) {
if (r == arr[j]) {
--i;
f = false;
break;
}
}
if (f)
arr.push(r);

}
return arr;
}

function findMinAndMax() {
var a = randNumArr(20);
window.console.log(a);
var j = 1;
var str = "总共" + (a.length) + "个元素\n" + a;
for ( var i = 0; i < a.length - 1; i++) {
if (a[i] < a[j]) {
j = i;
}
}
str += "\n最小元素:" + a[j] + " 序号为:" + j + ";";
j = 1;
for ( var i = 0; i < a.length - 1; i++) {
if (a[i] > a[j]) {
j = i;
}

}
str += " 最大元素:" + a[j] + " 序号为:" + j;
return str;

}

function printNum() {

alert(findMinAndMax())

}
printNum();
</script>
</head>
<body>

</body>
</html>
我写了一个用的是javascript,我测试了一下应该没有问题。有问题联系我。随机生成是不相同的数字。
相似回答