在编程中,do ... while循环的工作方式与while循环相同,主要区别是在块执行结束时评估指定的布尔条件。这导致语句至少执行一次,以后的迭代取决于布尔表达式的结果。使用过程符号和布尔条件进行do ... while迭代。
在此循环中,首先,执行代码内部定义的块,然后检查给定条件。由于此属性,它也称为测试后循环。
一个do ... while循环是示例出口控制环路,因为在此代码指定条件的评估之前执行。它一直运行到布尔条件为真,一旦评估为假,则该循环在该时间点终止。
在Ruby中,do ... while循环是通过以下语法实现的:
loop do # 要执行的代码块 break if Boolean_Expression #使用break语句 end
范例1:
=begin
Ruby program to check whether the given
number is Armstrong or not using a do-while loop
=end
puts "Enter the number"
num=gets.chomp.to_i
temp=num
sum = 0
loop do
#do-while循环的实现
rem=num%10
num=num/10
sum=sum+rem*rem*rem
puts "Checking......"
if num==0
break
end
end
if(temp==sum)
puts "The #{temp} is Armstrong"
else
puts "The #{temp} is not Armstrong"
end输出结果
First run: Enter the number 135 Checking...... Checking...... Checking...... The 135 is not Armstrong Second run: Enter the number 1 Checking...... The 1 is Armstrong
范例2:
=begin
Ruby program to check wether the given number
is having five or not using do-while loop
=end
puts "Enter the number"
num=gets.chomp.to_i
temp=num
sum = 0
flag=false #标志是一个布尔变量
loop do
#do-while循环的实现
rem=num%10
num=num/10
if(rem==5)
flag=true #如果发现存在,则标志为真
end
puts "Checking......"
if num==0
break
end
end
if(flag==true)
puts "We have found the presence of five in #{temp}"
else
puts "We have not found the presence of five in #{temp}"
end输出结果
First run: Enter the number 1234566 Checking...... Checking...... Checking...... Checking...... Checking...... Checking...... Checking...... We have found the presence of five in 1234566 Second run: Enter the number 198762 Checking...... Checking...... Checking...... Checking...... Checking...... Checking...... We have not found the presence of five in 198762