我正在尝试将数字1-10分配给两个变量。如果数字大于max,则使用该数字更新max,如果数字小于min,则使用更新min。随着生成的数量不断更新总数。我认为我有正确但无论什么时候产生。然后在最后我必须平均。这个数字不是随机的,并且会停留在相同的几个数字上。不知道我有什么不对。
package java_programming;
import java.util.Random;
public class Jp{
public static void main(String[] args){
//The Power Operation
double power = Math.pow(5.0,3.0);
//The Square Root Operation
double root = Math.sqrt(12.0);
//The Max Operation
double Maxi = Math.max(23.4, 23.5);
//The Min Operation
double Mini = Math.min(23.4, 23.5);
//The Random Opeartion
double rand = Math.random();
System.out.println("Results");
System.out.println("Math.pow = " + power);
System.out.println("Math.sqrt = " + root);
System.out.println("Math.max = " + Maxi);
System.out.println("Math.min = " + Mini);
System.out.println("Math.random = " + rand);
Jp rs = new Jp();
System.out.println("Min value");
rs.randomStudy();
}
public void randomStudy(){
int total = 0;
int max = -1;
int min = 11;
int iterations = 1000;
Random ran = new Random();
for(int i = 0; i < iterations; i++){
int count = ran.nextInt(10);
min = Math.min(count, min);
max = Math.max(count, max);
total += count;
}
System.out.println("Result of max: " + max);
System.out.println("Result of min: " + min);
System.out.println("Average: " + (1.0 * total / iterations));
}
}
答案 0 :(得分:2)
仅关注sorted_students = sort(students, key=lambda s:s.score)
:
randomStudy()
更新方法:
public void randomStudy()
{
int total = 0;
int max = -1;
int min = 11;
int i = 0;
Random ran = new Random();
while (i < 1001)
{
for(int count = 1; count<=10;count++)
count = ran.nextInt(11);
if(total < min)
min = total;
if(total>max)
max = total;
System.out.println("Result of max: " + max);
System.out.println("Result of min: " + min);
double average = total/1000;
System.out.println("Average: " + average);
i++;
}
}
编辑问题:
public void randomStudy()
{
int total = 0;
int max = -1;
int min = 11;
int iterations = 1000;
Random ran = new Random();
for(int i = 0; i < iterations; i++)
{
int count = ran.nextInt(11);
min = Math.min(count, min);
max = Math.max(count, max);
total += count;
}
System.out.println("Result of max: " + max);
System.out.println("Result of min: " + min);
System.out.println("Average: " + (1.0 * total / iterations));
}
这将循环1000 * 1000(1000000)次,这可能比您尝试做的多一点
要获取随机数[1,10]而不是[0,10],请使用[...]
while(i < 1001)
{
for(int j = 0; j < 1000; j++)
[...]
代替(How do I generate random integers within a specific range in Java?)