Problems computing on average in Java

Asked

Viewed 222 times

3

I’m trying to make a program that calculates the average between 4 values.

Code:

    private void botao1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    int n1 = Integer.parseInt(txt1.getText());
    int n2 = Integer.parseInt(txt2.getText());
    int n3 = Integer.parseInt(txt3.getText());
    int n4 = Integer.parseInt(txt4.getText());
    float notaf = (n1+n2+n3+n4)/4;
    res.setText(Float.toString(notaf));
}           

The problem is that when I have used the average result (notaf) it always comes as an integer (7.0, 8.0, 3.0) and does not come with the decimal numbers (7.5, 8.5, 3.5) where I made a mistake?

Print of the program:

inserir a descrição da imagem aqui

(The average in this case should be 6.75)

2 answers

4

Your problem is that all variables are of the type int. If you do operations with integers only, the result is also integer, always ignoring(note, it ignores and does not round!) the decimal part.

If you do float notaf = (n1+n2+n3+n4)/4f;, to say that the operator is float would be enough to work as you want.

4


The question already answers where the problem is. Note that the 4 notes are of the type int. This type, as its name implies, only accepts integers. You have to change the type of variables, and consequently of conversions. In case you should use the float (can be discussed if this type is also suitable, but will solve this exercise).

private void botao1ActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    float n1 = Float.parseFloat(txt1.getText());
    float n2 = Float.parseFloat(txt2.getText());
    float n3 = Float.parseFloat(txt3.getText());
    float n4 = Float.parseFloat(txt4.getText());
    float notaf = (n1+n2+n3+n4)/4;
    res.setText(Float.toString(notaf));
}  

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.