Answer the question
In order to leave comments, you need to log in
How to correctly write the conditions for the calculator in js: else if?
Hello! Please tell me how to write an algorithm for the conditions of the calculator.
Let's say there is a room 30 * 4.5 * 10 and there is a form for filling in the fields of length, width and height of some object.
You need to check the values from the above fields. They should not exceed the size of the room. How to check them if users can enter the dimensions of an item in any order in any field?
I got the following condition:
If at least 1 value is greater than 30, then display a message, otherwise
--- if 2 of the values are greater than 10, then display a message, otherwise
------- if at least one of the remaining values is greater than 4.5 , then display a message, otherwise
------------- execute the function.
var length,
width,
height,
sum,
message = 'Габариты предмета превышают размеры помещения';
if (length > 30 || width > 30 || height > 30) {
alert( message );
}
else if ((length > 10 && width > 10) || (height > 10 && width > 10) || (length > 10 && height > 10)) {
alert( message );
}
else if (length > 4.5 && width > 4.5 && height > 4.5) {
alert( message );
}
else {
sum = length * width * height
}
Answer the question
In order to leave comments, you need to log in
It's kind of hard for you. Why not do the following: add the values into two arrays - the dimensions of the room and the dimensions of the object, sort the arrays and simply check that no element of the first array is less than the corresponding element from the second? Something like this:
const
roomSizes = [ 30, 4.5, 10 ].sort((a, b) => b - a),
thingSizes = [ length, height, width ].sort((a, b) => b - a);
if (roomSizes.some((n, i) => n < thingSizes[i])) {
alert('всё плохо');
}
We put the values in an array, sort by value from largest to smallest, check the first for > 30, the second for > 10 and the third for > 4.5
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question