gpt4 book ai didi

Ruby 嵌套每个 do 循环

转载 作者:数据小太阳 更新时间:2023-10-29 07:45:37 25 4
gpt4 key购买 nike

我试图通过让这个程序运行来理解嵌套循环。如果可能的话,我想使用“每次做”的循环方式。现在循环执行所有第一个循环,然后是第二个……等等……我想做的是,执行第一个循环 1 次,然后下降到第二个循环一次……等等。这是我的代码(粘贴在下面)

期望的输出是这样的:

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

最佳答案

我认为你不必运行三个循环,下面会给出想要的输出

(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

关于Ruby 嵌套每个 do 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8149099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com