Algorithm that reads three numbers and displays the result of the sum of the first two and multiplied by the third

Asked

Viewed 559 times

0

Follow my code below, however does not return correct the result, if I put as input 2, 2, 3 was to appear 12, but appears 6

public class Exercicio2 {

@SuppressWarnings("unused")
public static void main(String[] args) {
    Scanner entrada = new Scanner(System.in);
    int i = 0;
    int[] soma = new int[3];
    int numero1, numero2 = 0;
    int total = 0;
    while(i < 3){
        System.out.println("Informe um numero[" + i + "]");
        soma[i] = entrada.nextInt();
        soma[i] += soma[i];
        total = soma[i];
        i++;
    }
    System.out.println(total);
   }
 }

2 answers

1

In this line

soma[i] += soma[i];

you are multiplying what has been entered by 2. That is, if you have entered 2 in index 0 you are doing sum[0] = sum[0] + sum[0]

What you should do is a cycle where you just log in:

for(int i = 0; i < 3; i++)
{
    System.out.println("Informe um numero[" + i + "]");
    soma[i] = entrada.nextInt();
}

And then you do the math:

total = (soma[0] + soma[1]) * soma[2];

Final code:

public class Exercicio2 {

@SuppressWarnings("unused")
public static void main(String[] args) {
    Scanner entrada = new Scanner(System.in);
    int[] soma = new int[3];
    int total = 0;
    for(int i = 0; i < 3; i++)
    {
        System.out.println("Informe um numero[" + i + "]");
        soma[i] = entrada.nextInt();
    }
    total = (soma[0] + soma[1]) * soma[2];
    System.out.println(total);
   }
 }

0

I would only have to check the steps taken by while, received the first number, incremented the variable i, and contains the value 1 it is because already received the first and the second number, then makes the sum, if it contains the value 2 is because it received the third so it makes the multiplication.

public static void main(String []args){
        Scanner entrada = new Scanner(System.in);
        int i = 0;
        // Alterei o nome da variavel, soma para numeros.
        int[] numeros = new int[3];
        // Criei outra variavel int com nome soma.
        int soma = 0;
        // int numero1, numero2 = 0; -> Não tem utilidade
        int total = 0;
        while(i < 3){
            System.out.println("Informe um numero[" + i + "]");
            numeros[i] = entrada.nextInt();
            // Verifica se já recebeu o primeiro numero, então faz a soma do primeiro com o segundo
            if (i == 1) {
                soma = numeros[0] + numeros[1];
            }
            // Ultima etapa, multiplica pelo terceiro.
            if (i == 2) {
                total = soma * numeros[i];
            }
            i++;
        }
        System.out.println(total);
    }

Browser other questions tagged

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