简体   繁体   中英

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; same with 5/4 which ends up as 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. The JRE will then do floating point division and produce a double. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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