我想打印出Math.random()少于0.5的次数以及有多少次数大于0.5。所以我使用int sum变量并每次增加它,如代码所示:
package shapes;
public class Main {
public static void main(String[] args) {
for (int i=1; i<6; i++){
int sum1=0;
if(Math.random()<0.5){
System.out.println("head");
System.out.println(Math.random());
sum1++;
System.out.println("sum of head"+sum1);
}else {
int sum2=0;
System.out.println("tail");
System.out.println(Math.random());
sum2++;
System.out.println("sum of tail"+sum2);
}
}
}
}
我的输出是:
tail
0.2420579681161944
sum of tail1
head
0.712979930711983
sum of head1
tail
0.28072067461911476
sum of tail1
head
0.5897197845744805
sum of head1
head
0.6735600614954825
sum of head1
我希望输出如下:
tail
0.2420579681161944
head
0.712979930711983
tail
0.28072067461911476
head
0.5897197845744805
head
0.6735600614954825
sum of head 3
sum of tail 2
我实际上试图将sum1 ++和sum2 ++放在不同的地方,但没有奏效。 感谢
答案 0 :(得分:1)
每次在for循环中将sum重置为0。将你的sums变量声明移出循环。
int sum1=0;
int sum2=0;
for (int i=1; i<6; i++){
double val = Math.random();
if(val<0.5){
sum1++;
}else {
sum2++;
}
System.out.println("sum of head "+sum1);
System.out.println("sum of tail "+sum2);
}
答案 1 :(得分:0)
做:
public static void main(String[] args) throws IOException
{
int sum1=0,sum2=0;
for (int i=1; i<6; i++){
if(Math.random()<0.5){
System.out.println("head");
System.out.println(Math.random());
sum1++;
}else { // end of if
System.out.println("tail");
System.out.println(Math.random());
sum2++;
}// end of else
}// end of for
System.out.println("sum of head "+sum1);
System.out.println("sum of tail "+sum2);
}// end of main