Zložitejšie kalkulačka - vie násobiť s medzivýsledky ako na papieri
Ukážkový program Zložitejšie kalkulačka, ktorý vie násobiť s medzivýsledky ako na papieri. Vrátane zdrojového kódu v jazyku Ruby.
# returns string with chosen number of "-" def make_line(length) s = "" length.times {s << "-"} return s end # provides safety input of natural number def enter_natural(msg) a = 0 while (a <= 0) puts msg a = gets.strip.to_i puts "Cislo nesmi byt mensi nebo rovne nule" if (a <= 0) end return a end puts "Vitejte v programu kalkulacka\n\n" a = enter_natural("Zadejte prvni cislo:") b = enter_natural("Zadejte druhe cislo:") # sefety input of operator opr = "" operators = ["+", "-", "*"] while (! operators.include?(opr)) puts "Zadejte operator[+/-/*]: " opr = gets.strip puts "Chybne zadany operator." if (! operators.include?(opr)) end output = [] output << a.to_s output << opr + b.to_s # underline result output << make_line(output.sort_by{|s| s.length}[-1].length) case opr when "+" output << (a + b).to_s when "-" output << (a - b).to_s when "*" product = (a * b).to_s # partial results if (b > 9) (b.to_s.length - 1).downto 0 do |i| output << (b.to_s[i].chr.to_i * a).to_s end output << make_line(product.length) end output << product end # formating output longest = output.sort_by{|s| s.length}[-1].length output.length.times do |i| if (output[i].length < longest) difference = longest - output[i].length # reduce number of whitespaces from line 4 if (i > 3) && (i < output.length - 2) difference -= (i - 3) end difference.times { output[i] = " " + output[i] } end end # displaying output puts "\n\n" output.length.times { |i| puts output[i] + "\n"}