Read quantity until you reach -1

Asked

Viewed 60 times

0

I worked in this exercise of the facu:

MAKE a program with a method ( exercicio06 ) to:

read two integers (a) and (b) from the keyboard, read other integer values from the keyboard one at a time, until the last value is equal to (-1). for all values in the open range ]a:b[; compute and show the sum of the squares of the inverses (1/x2 ). TIP: Avoid division by zero using a double alternative.

My input is this,: inserir a descrição da imagem aqui

my way out is this:

inserir a descrição da imagem aqui

If anyone can help you with anything,,

thanks a lot guys.

  • 2

    do not put picture in questions, put only text, because if someone tests your code will have to type it all, can not copy and paste!

1 answer

0

What is happening is that you read the numbers and, after the -1 is found, exit the while. At that moment, your x is worth 0 and does not fall within the if, so your code ends.

The exercise calls for something a little different than what you’re doing as well. The sum of the inverses of the squares would be to add all the inverses of the squares of the numbers within the specified range.

Ex:

a = 5
b = 8

Números digitados: 1 3 6 7 8 10 -1

Resultado = 1/(6^2) + 1/(7^2) + 1/(8^2)

Como somente 6, 7 e 8 estão no intervalo entre 5 e 8, somente os seus inversos são calculados

What I would recommend is that you read the numbers and, each time you read one, check if it is in the specified range and, if it is, add the inverse of its square in the result. When you read the -1, exits the loop and prints the result on the screen.

  • It can simply use the while instead of the do...while to verify the -1 before executing the rest of the code, certain?

  • Yeah, but her code is miscalculating, so just doing it wouldn’t solve it. The idea I wanted to pass on in the answer is to follow more or less in this line, but correcting the calculation and without giving the answer itself :)

Browser other questions tagged

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