Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculations coming out to 0.0?

Tags:

java

arrays

loops

A simple percentage calculation. It wont return a value except 0.0 and I think once or twice it returned 100.0%. Other than that it won't do a thing. I have tried playing with the code in several different ways and it just wont work.

for (int loop = 1; loop < loopCount; loop++)
            {
                aa = r.nextInt(10+1);
                abc = (int) aa;

                String[] userAnswer = new String[x];

                int totalQues = (correctAnswer + wrongAnswer), actualQues = (totalQues - 1);

                if(abc < x)
                {
                    userAnswer[abc] = JOptionPane.showInputDialog(null,"Question "+quesNum+"\n\n"+questions[abc]+"\n\nA: "+a[abc]+"\nB: "+b[abc]+"\nC: "+c[abc]+"\nD: "+d[abc]+"\nCorrect Answers: "+correctAnswer+"\nWrong Answers: "+wrongAnswer+"\nTotal Questions: "+totalQues);

                    if(userAnswer[abc].equals(answers[abc]))
                    {
                        correctAnswer++;
                    }
                    else
                    {
                        wrongAnswer++;
                    }//else

                    if(actualQues == x);
                    {
                        score = (correctAnswer / actualQues) * 100;

                        JOptionPane.showMessageDialog(null,"The test is finished.");

                        JOptionPane.showMessageDialog(null,"You scored "+score+"%");

                    }//if

                }//if

            }//for
like image 896
Nick Gibson Avatar asked Nov 26 '25 21:11

Nick Gibson


2 Answers

Change

score = (correctAnswer / actualQues) * 100;

to

score = ((double)correctAnswer / actualQues) * 100;
like image 177
Jonathon Faust Avatar answered Nov 28 '25 10:11

Jonathon Faust


Since you are doing integer division, the result of that operation will always be either 0 or 1. Instead, try casting to a floating-point number prior to dividing:

score = (int)((correctAnswer / (1.0 * totalQues)) * 100);
like image 35
Justin Ethier Avatar answered Nov 28 '25 09:11

Justin Ethier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!