Scanner s = new Scanner(System.in);
System.out.println("Type a number");
int n = s.nextInt();
int start = 0;
int largest = 0;
int occurrence = 0;
while(n > start){
int number = (int)(Math.random()*100);
if(number > largest){
largest = number;
}
n--;
System.out.print(number+" ");
}
System.out.println("max is "+largest);
System.out.println("Occurrence is "+occurrence);
我希望能够找到最大的int的出现,我不知道如何以一种相当简单的方式这样做。我尝试在occurrence++;
下添加largest = number;
,但这不起作用。
例如,我输入6
作为输入,我会得到随机数54, 74, 61, 89, 13, 89
。
所需的输出为max is 89. Occurrence is 2.
另外,我试图只让代码每行只打印10个数字,然后它会跳到下一行并继续。
答案 0 :(得分:1)
1
醇>
您可以使用
if(number > largest){
largest = number; // found larger value
occurrence = 1; // reset occurrence back to initial
}else if(number == largest){
occurrence++; // keep track of same large value
}
答案 1 :(得分:0)
您需要使用else if
条件来检查这样的相等
Scanner s = new Scanner(System.in);
System.out.println("Type a number");
int n = s.nextInt();
int start = 0;
int largest = 0;
int occurrence = 1;
while(n > start){
int number = (int)(Math.random()*100);
if(number > largest){
largest = number;
}else if(number == largest){
occurrence++;
}
n--;
System.out.print(number+" ");
}
System.out.println("max is "+largest);
System.out.println("Occurrence is "+occurrence);
P.S - 初始化occurrence = 1
,因为至少有一次会出现最大数字
答案 2 :(得分:0)
我想你差不多了。基本上,您错过了检查新随机数是否等于当前最大数字。类似的东西:
library(tidyr)
df %>% spread(b, c)
另外,请记住在找到新的最大号码时重置发生次数:
if (number == largest) {
occurrences++;
}