2011-11-16 118 views
3

我想通過讓程序工作來理解嵌套循環。如果可能的話,我想使用循環的「每個做法」。現在循環執行所有的第一個循環,然後第二個......等等......我想要做的是,執行第一個循環1次,然後一次下降到第二個循環......等等。這裏是我的代碼(粘貼以下)Ruby嵌套每個循環

期望輸出會是這樣的:

index      3.0     3.0 
+-------------------------------------------------------+ 
0       -23.4    -23.4 
1      -2226.74    -2226.74 
2     -1.93464e+07   -1.93464e+07 

代碼

class LogisticsFunction 
    puts "Enter two numbers, both between 0 and 1 (example: .25 .55)." 
    puts "After entering the two numbers tell us how many times you" 
    puts "want the program to iterate the values (example: 1)." 

    puts "Please enter the first number: " 
    num1 = gets.chomp 

    puts "Enter your second number: " 
    num2 = gets.chomp 

    puts "Enter the number of times you want the program to iterate: " 
    iter = gets.chomp 

    print "index".rjust(1) 
    print num1.rjust(20) 
    puts num2.rjust(30) 
    puts "+-------------------------------------------------------+" 

    (1..iter.to_i).each do |i| 
    print i 
    end 
    (1..iter.to_i).each do |i| 
     num1 = (3.9) * num1.to_f * (1-num1.to_f) 
     print num1 
    end 
     (1..iter.to_i).each do |i| 
     num2 = (3.9) * num2.to_f * (1-num2.to_f) 
      print num2 
     end 
end 
+0

你只希望這在給定的方式顯示? –

回答

4

我覺得你不必有三個循環中運行,下面將給願望輸出

(1..iter.to_i).each do |i| 
    print i 
    num1 = (3.9) * num1.to_f * (1-num1.to_f) 
    print num1.to_s.rjust(20) 
    num2 = (3.9) * num2.to_f * (1-num2.to_f) 
    print num2.to_s.rjust(30) 
end 
+0

運行此代碼:http://www.pastie.org/2871457給我這個錯誤,1logistics_functionz.rb:23:在'在中的塊:未定義的方法'rjust'爲-23.4:Float(NoMethodError ) \t從logistics_functionz.rb:20:在'每個 ' \t從logistics_functionz.rb:20:在'<類:LogisticsFunction>' 從logistics_functionz.rb \t:1:在'

「 – jimmyc3po

+0

改變了代碼,需要將字符串中的num1和num2轉換爲使用rjust方法。現在試試 –

+0

酷!這正是*我正在嘗試做的,也是編碼風格。非常感謝您的幫助,非常感謝!我也學到了一些東西。 :) – jimmyc3po

1

難道不這樣的事情解決問題了嗎?

(1..iter.to_i).each do |i| 
    num1 = (3.9) * num1.to_f * (1-num1.to_f) 
    print num1 
    num2 = (3.9) * num2.to_f * (1-num2.to_f) 
    print num2 
end 

從我能看到你甚至不使用i變量。所以從理論上講,你可以只是做

iter.to_i.times do 
    # stuff 
end 
3

您的循環實際上並沒有嵌套。它們實際上是一個接一個的。這就是爲什麼他們一個接一個地運行。要嵌套它們 - 你必須把它們放在彼此之內。例如:

沒有嵌套

(1..iter.to_i).each do |i| 
    # stuff for loop 1 is done here 
end # this closes the first loop - the entire first loop will run now 

(1..iter.to_i).each do |j| 
    # stuff for loop 2 is done here 
end # this closes the second loop - the entire second loop will run now 

嵌套:

(1..iter.to_i).each do |i| 
    # stuff for loop 1 is done here 
    (1..iter.to_i) .each do |j| 
    # stuff for loop 2 is done here 
    end # this closes the second loop - the second loop will run again now 
    # it will run each time the first loop is run 
end # this closes the first loop - it will run i times 
+1

這也有幫助。謝謝。 – jimmyc3po