检查用户的输入数字是正数还是负数,如果输入数字是负数,则给出错误

时间:2017-09-04 03:49:29

标签: lua

我正在尝试创建一个程序,它接受用户的输入宽度和高度,并输出矩形的区域和周长。我还希望程序检查用户是否为宽度或高度设置正值或负值。如果用户输入负值,我希望它显示错误。这是我迄今为止所拥有的,但它有点跳过并仍然计算。

local width, height, area, perimeter

-- intro text and user inputs
print("Welcome to the Rectangle Area & Perimeter Calculator")

print("Enter Rectangle Width")
width = io.read("n")
if width <0 
then print "Error: Please enter a positive value for width"
end

print("Enter Rectangle Height")
height = io.read("n")
if height <0
then print "Error: Please enter a positive value for height"
end 

--Calculator
area = width * height
print("The area of the rectangle is ", area)
perimeter = 2 * (width + height)
print("The perimeter of the rectangle is ", perimeter)

1 个答案:

答案 0 :(得分:3)

编辑2:您可以使用repeat until循环,因此代码块将重复,直到用户输入数字为正 strong>,请尝试以下代码

local width, height, area, perimeter

-- intro text and user inputs
print("Welcome to the Rectangle Area & Perimeter Calculator")

repeat
print("Enter Rectangle Width")
width = io.read("n")
  if(width < 0)
    then print("error : enter a positive value")
  end
until width > 0 

repeat
print("Enter Rectangle Height")
height = io.read("n")
  if height <0
    then print "Error: Please enter a positive value for height"
  end  
until height > 0 

--Calculator
area = width * height
print("The area of the rectangle is ", area)
perimeter = 2 * (width + height)
print("The perimeter of the rectangle is ", perimeter)