简体   繁体   English

如何更改它以接受双精度并使 factor2 不返回零?

[英]How can I change this to accept doubles and make factor2 not return zero?

The code below is supposed to randomly create two integer numbers which will then be displayed to a user who then needs to divide the two numbers;下面的代码应该随机创建两个整数,然后将其显示给需要将这两个数字相除的用户; however, when I try to change the answer or response to both be doubles it doesn't work.但是,当我尝试将答案或响应更改为双打时,它不起作用。 If you do run it as is and get a question such as 1/5 then the answer ends up being 0 since it's an integer;如果你按原样运行它并得到一个诸如 1/5 之类的问题,那么答案最终是 0,因为它是一个整数; same with 5/4 which ends up as 1.与 5/4 相同,最终为 1。

//Variables
String name;
String probType;
String longProbType;
int numProb;
int loFactor;
int hiFactor;
int factor1;
int factor2;
int answer;
int response;
int score;
double scorePct;

case "D":
    for(int i = 0; i < numProb; i++) {
        factor1 = random.nextInt(hiFactor - loFactor + 1) + loFactor;
        factor2 = random.nextInt(hiFactor - loFactor + 1) + loFactor;
        if(factor2 == 0) {
            factor2 += 1;
        }
        System.out.print(String.format("\n%d / %d = ", factor1, factor2));
        response = input.nextInt();
        input.nextLine();
        
        answer = factor1 / factor2;
        
        if(answer == response) {
            score += 1;
            System.out.println("Correct!");
            history[i] = String.format("%d / %d = %d, Correct, correct answer is %d", factor1, factor2, response, answer);
        } else {
            System.out.println(String.format("Incorrect! Correct answer is %d", answer));
            history[i] = String.format("%d / %d = %d, Incorrect, correct answer is %d", factor1, factor2, response, answer);
        }
    }
    
    System.out.println("\nSession Summary");
    System.out.println(String.format("%d problems, %d correct", numProb, score));
    
    scorePct = ((double)score / numProb) * 100;
    System.out.println(String.format("Score is  %.1f\n", scorePct));
    
    System.out.println("\nProblems");
    for(int i = 0; i < numProb; i++) {
        System.out.println(history[i]);
    }
    
    System.out.println(outromessage);
    break;

For the division, you need to cast one of the int values to a double.对于除法,您需要将其中一个 int 值转换为双精度值。 The JRE will then do floating point division and produce a double.然后 JRE 将进行浮点除法并产生一个双精度数。 This result will also need to be captured in a double.这个结果也需要用双精度来捕获。

double result = factor1 / (double) factor2;

Note that testing floating point equality can be tricky and produce false negatives/positives.请注意,测试浮点相等性可能会很棘手,并且会产生误报/误报。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM