Ruby while循环示例

while循环

在计算机编程中,while循环适用于特定的布尔条件。重复一直进行到指定的布尔条件不为假为止。您也可以将其称为if语句的迭代。该while循环的两件事情包括:

  1. 表达式或布尔条件

  2. 循环体

while循环的方式工作是测试给定的条件,如果结果来作为以后真,则执行循环里面写的表达,否则循环被终止。这也称为预测试循环,因为条件是在执行块之前评估的。这是Entry Control Loop的示例,因为在执行循环主体之前先检查条件。

在Ruby编程语言中,while循环通过以下语法实现:

    while (Boolean condition )
        # 要执行的代码
    end

范例1:

=begin 
Ruby program to Calculate the factorial of 
given number using while loop
=end

puts "Enter the number"
num=gets.chomp.to_i

i = 1
fact = 1

while i <= num  #while循环的实现
	fact *= i
	i += 1
end

puts "The factorial of #{num} is #{fact}"

输出结果

Enter the number
5
The factorial of 5 is 120

范例2:

=begin 
Ruby program to check whether the given 
number is palindrome or not using while loop
=end

puts "Enter the number"
num=gets.chomp.to_i

temp=num
sum = 0

while num!=0  #while循环的实现
	rem=num%10
	num=num/10
	sum=sum*10+rem
end

if(temp==sum)
	puts "The #{temp} is a palindrome"
else
	puts "The #{temp} is not a palindrome"
end

输出结果

First run:
Enter the number
121
The 121 is a palindrome

Second run:
Enter the number
566
The 566 is not a palindrome

范例3:

=begin 
Ruby program to check whether the given number 
is Armstrong or not using while loop
=end

puts "Enter the number"
num=gets.chomp.to_i

temp=num
sum = 0

while num!=0  #while循环的实现
	rem=num%10
	num=num/10
	sum=sum+rem*rem*rem
end

if(temp==sum)
	puts "The #{temp} is Armstrong"
else
	puts "The #{temp} is not Armstrong"
end

输出结果

First run:
Enter the number
153
The 153 is Armstrong

Second run:
Enter the number
1
The 1 is Armstrong

Third run:
Enter the number
2332
The 2332 is not Armstrong

无限while循环

当您必须故意进行无限循环时,可能会发生这种情况。循环本身不会终止,您必须应用一个称为“ break”的附加语句来停止循环。通过以下示例可以证明这一点:

=begin 
Ruby program to make an infinite loop using while loop
=end

num=9

while num!=0  #while循环的实现
	puts "Nhooo.com"
	break
end

输出结果

Nhooo.com

您会发现,循环将在获得显式的break语句后立即终止。

让我们总结一下:

一个while循环是一款入门控制回路只执行一个给定的条件计算为真。Ruby使用while关键字定义while循环。

一个无限循环是一个循环,永远不会结束本身,即需要一个明确的退出声明。