Division does not display numbers after the comma

Asked

Viewed 43 times

0

My algorithm in all tests println(), is working and in logic also however, the numbers after the comma it does not demonstrate.

public class Exe27 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Scanner scan = new Scanner (System.in);

        int dividendo = 1;
        int numero = 0;
        double numHarmonico = 0;

        System.out.println("Sistema Harmônico");
        System.out.println("Digite em até que número a série irá");
        numero =scan.nextInt();

        for(int i = 1;i <= numero; i++) {

            numHarmonico += dividendo/i;
        }

        System.out.printf("%.2f", numHarmonico);
        scan.close();
    }

}

2 answers

3

It is dividing by an integer number, so the result will be integer, even if it is later saved in a variable of type double. First he makes the account and then he keeps it, the moment he makes the account using integers the result does not consider where it will be stored, only what he needs for the account. Changing the type of one of the operands solves the question:

import java.util.*;

class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner (System.in);
        System.out.println("Sistema Harmônico");
        System.out.println("Digite em até que número a série irá");
        int numero = scan.nextInt();
        double numHarmonico = 0;
        for (int i = 1; i <= numero; i++) numHarmonico += 1.0 / i;
        System.out.printf("%.2f", numHarmonico);
        scan.close();
    }
}

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

2


As @Maniero has already said, the problem lies in the division of integers.

Another possibility is to convert the value during splitting:

numHarmonico += Double.valueOf(dividendo)/i;

Or

numHarmonico += (double)dividendo/i;

This is just an example, keep in mind that every iteration you will cast.


The complete code would look more or less like this:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner (System.in);

        int dividendo = 1;
        int numero = 0;
        double numHarmonico = 0;

        System.out.println("Sistema Harmônico");
        System.out.println("Digite em até que número a série irá");
        numero =scan.nextInt();

        for(int i = 1;i <= numero; i++) {
            // Outro exemplo de conversão
            // numHarmonico += Double.valueOf(dividendo)/i;
            numHarmonico += (double)dividendo/i;
        }

        System.out.printf("%.2f", numHarmonico);
        scan.close();
    }
}

See online: https://repl.it/repls/WorthlessBleakScientist

Browser other questions tagged

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