Delphi 7-多个,如果未显示正确的标签

Sul*_*afi 0 delphi conditional if-statement delphi-7

我正在尝试在Delphi 7中进行血压类别检查,而我刚认识Delphi已有几个星期了。问题是,每当我输入大于120的数字时,标签标题始终显示正常。这是我的代码:

procedure TForm1.Button1Click(Sender: TObject);
var a,b:real;
begin
a:=strtofloat(edit1.Text);
if (a<120) then label1.caption:='optimal'
else if (a>120) then label1.caption:='normal'
else if (a<130) then label1.caption:='normal'
else if (a>130) then label1.caption:='normal high'
else if (a<140) then label1.caption:='normal high'
else if (a>140) then label1.caption:='grade 1 hypertension'
else if (a<160) then label1.caption:='grade 1 hypertension'
else if (a>160) then label1.caption:='grade 2 hypertension'
else if (a<180) then label1.caption:='grade 2 hypertension'
else if (a>181) then label1.caption:='grade 3 hypertension'

end;

end.
Run Code Online (Sandbox Code Playgroud)

可能是一些常见的错误,但我仍然无法自己弄清楚,任何帮助都会有很大帮助,谢谢。

Ken*_*ite 5

您的代码不正确。它仅检查两个值,分别是< 120> 120。没有别的东西可以测试了。

当寻找一个范围内的值时,您需要测试范围的两端,如下所示:

procedure TForm1.Button1Click(Sender: TObject);
var 
  a: real;
begin
  a:=strtofloat(edit1.Text);
  if (a < 120) then
    Label1.Caption := 'Optimal'
  else if (a >= 120) and (a < 130) then
    Label1.Caption := 'Normal'
  else if (a >= 130) and (a < 150) then
    Label1.Caption := 'Normal high'
  else if (a >= 150) and (a < 160) then
    Label1.Caption := 'Grade 1 hypertension'
  else if (a >= 160) and (a < 170) then
    Label1.Caption := 'Grade 2 hypertension'
  else if (a >= 170) and (a < 180) then
    Label1.Caption := 'Grade 3 hypertension'
  else
    Label1.Caption := 'Heart exploded from pressure';
end;
Run Code Online (Sandbox Code Playgroud)

(您的范围真的很混乱。您需要调整我的代码以满足您的实际范围要求,但是我发布的内容应该可以帮助您入门。)

由于不太可能有人将血压记录为浮点值(您的BP不太可能是121.6 / 97.2),因此您可能想使用整数代替,这会使代码更容易。

procedure TForm1.Button1Click(Sender: TObject);
var
  a: Integer;
begin
  a := StrToInt(Edit1.Text);
  case a of
    0..119:  Label1.Caption := 'Optimal';  // Probably want to test for too low
    120..129: Label1.Caption := 'Normal';
    130..149: Label1.Caption := 'Normal high';
    150..159: Label1.Caption := 'Grade 1 hypertension';
    160..169: Label1.Caption := 'Grade 2 hypertension';
  else
    Label1.Caption := 'Over 170! Danger!'
  end;
end;
Run Code Online (Sandbox Code Playgroud)