-2
import java.util.Random;
import java.util.Scanner; 

public class Carpim {
    Scanner input = new Scanner(System.in); 
    Random myRandom = new Random(); 

    public void determine(){ 



    int trueNumber = 0; 
    int wrongNumber = 0; 
    int total = 0; 
    int answer = 0;

    for (int i = 0; i < 5; ++i){
    int num1 = 1 + myRandom.nextInt(11);
    int num2 = 1 + myRandom.nextInt(11);
    int correctResult = num1 * num2;

    System.out.println( num1 + "*" + num2 + " What is the answer?");
    answer = input.nextInt();

    if (answer == correctResult){ 
        ++trueNumber; 
        ++total;
    }else if (answer != trueNumber){ 
        ++total; 
        ++wrongNumber; 
    }//end if statement

    }//end for loop 

    percentage(total, wrongNumber); 

    }//end method 
    private int percentage(int total, int wrongNumber){ 
        int percentage = (total - wrongNumber)/total; 

        System.out.println(total + " " + wrongNumber + " " + percentage ); 

        return percentage; 
    }//end private method. 

}//End Class

这是我的代码,当我运行此代码时,最后无法计算百分比。但是,它可以计算出 wrongNumber 和总数。你能帮我看看这段代码有什么问题吗?

4

4 回答 4

8

用整数除法整数在java中产生整数而不是浮点数

于 2012-06-06T18:36:17.257 回答
0

首先,除以整数将产生一个整数结果 - 丢弃数字的小数部分。您可以通过将代码更改为此来解决此问题:

double percentage = (double)(total - wrongNumber)/total;

...然后返回double.

此外,您正在丢弃percentage(). 我不认为您打算这样做,因此您希望将其保存在方法内部的某种变量中,然后打印或返回它。

于 2012-06-06T18:37:29.703 回答
0

您的私有方法应注意数据类型:

private double percentage(int total, int wrongNumber){ 
    double percentage = (double)(total - wrongNumber)/total; 

    System.out.println(total + " " + wrongNumber + " " + percentage ); 

    return percentage; 
}//end private method. 

您应该使用浮点数据类型将十进制值保留为 % 值。

如果您想要一种快速将百分比精确到小数点后 2 位的方法,您可以这样做:

double percentage = 56.4332893723;
percentage = ((int)(percentage*100))/100.0;    // instant 2-decimal conversion
于 2012-06-06T18:38:52.740 回答
0

在你的百分比函数中,你有int百分比。整数不能包含十进制值和 (total - wrongNumber) / total < 0;

于 2012-06-06T18:38:10.080 回答