java - 如何在 Java 中划分两个整数并返回一个 double

标签 java android

<分区>

我是 Android 的新手,我在使用我正在创建的数学应用程序时遇到了问题。

基本前提是向用户显示 0 到 20 之间的 2 个数字 (questionTextView),然后向用户显示包含 3 个错误答案和 1 个正确答案的网格。然后用户点击正确答案。

我遇到的问题是正确答案没有显示到小数点后两位。

例如问题:4/7

答案 1:12.59

答案 2:15.99

答案 3:9.93

答案4:0(应该是0.57)

我不明白为什么正确答案没有正确显示,因为我已将两个整数转换为 double 并包含十进制格式。

我试过 Math.round(),但我无法让它工作 - 可能是因为我在 for 循环中生成问题的方式????

正确显示错误的答案。

如有任何帮助,我们将不胜感激。

这是我的代码:

private static DecimalFormat df2 = new DecimalFormat("#.##");

public void generateQuestion(){

    //Create 2 random numbers between 0 and 20.
    Random rand = new Random();

    int a = rand.nextInt(21);
    int b = rand.nextInt(21);

    if (a==b){
        b = rand.nextInt(21);
    }

    questionTextView.setText(Integer.toString(a) + " / " + Integer.toString(b));

/*Create a random number between 0 and 3 to determine the grid square of 
the correct answer */
    locationOfCorrectAnswer = rand.nextInt(4);

    //Calculate the correct answer.
    double correctAnswer = (int)(((double)a/(double)b));

  //Generate an incorrect answer in case the correct answer is 
   randomly generated.
   double inCorrectAnswer;

    /*Loop through each square and assign either the correct answer or
    a randomly generated number. */
    for (int i=0; i<4; i++){
        if (i == locationOfCorrectAnswer){ 
            answers.add(df2.format(correctAnswer).toString());
        } else {
            inCorrectAnswer = 0.05 + rand.nextDouble() *20.0;

            while (inCorrectAnswer == correctAnswer){
                inCorrectAnswer = 0.05 + rand.nextDouble() *20.0;
            }
            answers.add(df2.format(inCorrectAnswer).toString());
        }
    }

    //Assign an answer to each of the buttons.
    button0.setText((answers.get(0)));
    button1.setText((answers.get(1)));
    button2.setText((answers.get(2)));
    button3.setText((answers.get(3)));

最佳答案

选择以下之一:

double correctAnswer = (double)a/b;

double correctAnswer = a/(double)b;

double correctAnswer = (double)a/(double)b;

关于java - 如何在 Java 中划分两个整数并返回一个 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38909968/

相关文章:

c# - 如何从 Android 应用程序中为 Android 类调用 Mono?

受设备音量影响的 Android Visualizer FFT/波形?

androidstudio 服务无法在 Androidx 中运行

java - 检查所有 Dto 成员中的 null 条件。如果不是,则将值设置为 pojo 类的相同属性

java - 单击项目后,如何从 RecyclerView 的适配器内的 drawable 更改 imageView 的图像?

java - Jhipster 没有创建我在 jhipster 命令时导入的实体

java - JIDE公共(public)层 undefined symbol sun.awt.image.CachingSurfaceManager

android - 还需要BaseGameUtils吗? (实现Android排行榜)

android - View 分隔线在我的 Android 导航中不可见

java - MySQL JDBC 计算行数失败