Ruby :: Aufgabe #168
1 Lösung
Zahlen umwandeln: Binär zu Dezimal
Anfänger - Ruby
von Nachbar
- 13.09.2017 um 14:19 Uhr
Schreibe eine Funktion, die Zahlen aus dem Dualsystem in Zahlen des Dezimalsystems umwandelt.
Beispiel:
Binär: 11010
Dezimal: 26
Beispiel:
Binär: 11010
Dezimal: 26
Lösungen:
Ruby-Code
=begin Binary to decimal converter and reverse By Lars I. for Train-your-Programmer Link: https://trainyourprogrammer.de/ruby #168 lines of code: 23 =end #============================================================================= def getBinary() =begin In: nothing Out: returns the entered binary number as a string =end #Section - Code #Section - Declaration input_okay = true bin = "" #Section - getting and checking the user-input loop do puts "Please enter your binary number." print "Your input = " bin = gets.chomp print "\n\n===============================================================================\n\n" #validating the input bin.each_char do |x| #filling the array with the single digits of the binary number if x != "0" && x != "1" #x == "0" || x == "1" #arr.push(x) #else input_okay = false break end end #breaking the loop if only 0's and 1's have been entered break if input_okay == true end #Section - Output return bin end #============================================================================= def convert() =begin In: nothing Out: nothing =end #Section - Code #Section - Get the number to be converted bin = getBinary() #Section - Converting the binary to a decimal number dec = bin.to_i(2) #Section - Output puts "The binary number #{bin} matches #{dec} in the decimal number system." end convert()