-
Notifications
You must be signed in to change notification settings - Fork 0
Add lesson-1 comments #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| # Идеальный вес. Программа запрашивает у пользователя | ||
| # имя и рост и выводит идеальный вес по формуле | ||
| # <рост> - 110, после чего выводит результат пользователю на экран | ||
| # с обращением по имени. Если идеальный вес получается отрицательным, | ||
| # то выводится строка "Ваш вес уже оптимальный" | ||
| puts 'Hello. Let me know your name' | ||
| name = gets.chomp | ||
| puts 'Fine, now i want to know your height' | ||
| height = gets.chomp.to_i | ||
| best_weight = height - 110 | ||
| if best_weight <= 0 | ||
| puts "Ok, #{name}, yor best weight is #{best_weight}" | ||
| else puts "Your weight is good" | ||
| end | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Как правило, условные выражения форматируют так: if <condition>
<code>
else
<code>
end |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| # Площадь треугольника. Площадь треугольника можно вычилсить, | ||
| # зная его основание (a) и высоту (h) по формуле: 1/2*a*h. | ||
| # Программа должна запрашивать основание | ||
| # и высоту треуголиника и возвращать его площадь. | ||
| puts 'Enter a:' | ||
| a = gets.chomp.to_f | ||
| puts 'Enter h' | ||
| h = gets.chomp.to_f | ||
| puts "S = #{0.5*a*h}" | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Стоит вычислять площадь заранее и присваивать результат локальной переменной, затем её здесь выводить чтобы разделить логику вычисления и вывода. |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| # Прямоугольный треугольник. | ||
| # Программа запрашивает у пользователя 3 стороны треугольника | ||
| # и определяет, является ли треугольник прямоугольным, | ||
| # используя теорему Пифагора (www-formula.ru) и выводит результат на экран. | ||
| # Также, если треугольник является при этом равнобедренным | ||
| # (т.е. у него равны любые 2 стороны), то дополнительно выводится информация о том, | ||
| # что треугольник еще и равнобедренный. | ||
| # Подсказка: чтобы воспользоваться теоремой Пифагора, | ||
| # нужно сначала найти самую длинную сторону (гипотенуза) | ||
| # и сравнить ее значение в квадрате с суммой квадратов двух остальных сторон. | ||
| # Если все 3 стороны равны, то треугольник равнобедренный и равносторонний, | ||
| # но не прямоугольный. | ||
| puts "Enter a b c of triangle (with delimiter ','):" | ||
| sides = gets.chomp.split(',').map {|i| Float(i) } | ||
| a = sides[0] | ||
| b = sides[1] | ||
| c = sides[2] | ||
| case sides.max | ||
| when a | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Подумай как можно это отрефакторить чтобы не считать три раза теорему Пифагора. |
||
| if (c**2 + b**2) == a**2 | ||
| puts 'triangle is rectangular' | ||
| end | ||
| when b | ||
| if (a**2 + c**2) == b**2 | ||
| puts 'triangle is rectangular' | ||
| end | ||
| when c | ||
| if (a**2 + b**2) == c**2 | ||
| puts 'triangle is rectangular' | ||
| end | ||
| else | ||
| puts "something went wrong" | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Почему что-то пошло не так? Треугольник может существовать, просто не быть прямоугольным. |
||
| end | ||
| if [a, c].include? b | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| puts 'triangle is equilateral and isosceles' | ||
| elsif a == b || a == c || b == c | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Подумай как ещё можно определить это условие. |
||
| puts 'triangle is isosceles' | ||
| end | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Обычно пишут в таком формате: if <condition>
<code>
else
<code>
end |
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| #Квадратное уравнение. Пользователь вводит 3 коэффициента a, b и с. Программа вычисляет дискриминант (D) и корни уравнения (x1 и x2, если | ||
| #oни есть) и выводит значения дискриминанта и корней на экран. При этом возможны следующие варианты: | ||
| # Если D > 0, то выводим дискриминант и 2 корня | ||
| # Если D = 0, то выводим дискриминант и 1 корень (т.к. они в этом случае равны) | ||
| # Если D < 0, то выводим дискриминант и сообщение "Корней нет" | ||
| #Подсказка: Алгоритм решения с блок-схемой (www.bolshoyvopros.ru). Для вычисления квадратного корня, нужно использовать | ||
| #Math.sqrt | ||
| # Например, | ||
| #Math.sqrt(16) | ||
| # вернет 4, т.е. квадратный корень из 16. | ||
|
|
||
| puts "Enter a b c (with delimiter ','):" | ||
| sides = gets.chomp.split(',').map {|i| Float(i) } | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Обычно используют Ещё можно применить сокращённую форму вызова метода в итераторе sides = gets.chomp.split(',').map(&:to_f)
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Второй момент, я догадываюсь почему, но |
||
| a = sides[0] | ||
| b = sides[1] | ||
| c = sides[2] | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Можно воспользоваться параллельным присваиванием: a, b, c = sidesА можно сразу работать через массив |
||
| if (d=b**2-4*a*c) == 0 | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. В данном случае присваивание лучше вынести за пределы |
||
| puts "x = #{(-b)/2*a}" | ||
| elsif d<0 | ||
| puts "no roots of equation" | ||
| elsif d>0 | ||
| puts "x1 = #{(-b+Math.sqrt(d))/(2*a)}\nx2 = #{(-b-Math.sqrt(d))/(2*a)}" | ||
|
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Здесь стоит разделить логику вывода и вычислений. Иначе трудно читать, поддерживать и ориентироваться. |
||
| end | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
По-моему, должно быть наоборот )