我只是想在Pascal上编写我的第二篇(是的,这对我来说绝对是新的)教学程序。我做了一次,使用"如果",这里是:
program DemoBool;
Var A: Boolean ; B: Boolean ;
C:Integer ; D:Integer ;
I:Integer;
begin
write('Enter A(1/0): '); readln(I);
if (I= 1)
then A:=true else A:=false;
writeln(A);
write('Enter B(1/0): '); readln(I);
if I=1
then B:=true else B:=false;
writeln(B);
write('enter C: '); readln(C);
write('enter D: '); readln(D);
IF ((A=B) AND (C>D)=TRUE OR NOT A )
THEN IF ((TRUE<>A) AND (C-D<3))
THEN writeln('a=b, c>d, or not A=true, (true<>a and c-d<3)=true')
ELSE writeln('a=b, c>d, or not A=true, (true<>a and c-d<3)=false')
ELSE writeln('a<>b, c<d, or not A=false') ;
readln;
end.
如果是最新情况,我该如何使用案例? 我可以写新的Var-s,F,F2-布尔然后以某种方式制作:
F:= ((A=B) AND (C>D)=TRUE OR NOT A ) ;
F2:= ((TRUE<>A) AND (C-D<3));
用例?
这对我来说真的不容易,但希望,我可以完成这项任务)对不起我的解释。谢谢你的关注
答案 0 :(得分:0)
您可以使用布尔值进行一些改进,但这是正常的,因为您学习了。
if (I= 1) then A:=true else A:=false;
您可以直接将A
的比较结果分配给I
等于1
A := (I = 1);
即使没有优化(TEST也不是SETZ指令),这会导致更好的字节代码。 Paren对只是为了便于阅读。
IF ((A=B) AND (C>D)=TRUE OR NOT A )
您无需将布尔操作的结果与true
的{{1}}进行比较。
false
表达式语句if ((a=b) and (c>d) or not a)
已经计算为布尔值。
如果你想使用(a=b) and (c>d)
表达式,让我们说替换程序的结尾:
case of
请注意,我使用潜伏评论的简化声明。
答案 1 :(得分:0)
据我所知,你坚持使用案例陈述。虽然我完全同意@lurker并假设case
语句在这里没用,但我有以下建议。
program DemoBool;
var
BitLogic: byte;
tmpb: byte;
A: Boolean;
B: Boolean;
C: Integer;
D: Integer;
I: Integer;
function GetBoolBit(const B: Boolean; Offset: byte): byte;
begin
if B then
begin
result := 1;
result := result shl Offset;
end
else
result := 0;
end;
begin
//input the values
BitLogic := GetBoolBit(A = B, 0);
tmpb := GetBoolBit(A, 1);
BitLogic := tmpb or BitLogic;//make comparison and store the result
// in bit-by-bit mode - every new boolean with the new offset
// the code is unscrolled here. We can optimize it writing the following instead:
// BitLogic := GetBoolBit(A, 1) or BitLogic;
tmpb := GetBoolBit(C > D, 2);
BitLogic := tmpb or BitLogic;
tmpb := GetBoolBit(C - D < 3, 3);
BitLogic := tmpb or BitLogic;
// we get the following the lower bit will store the first boolean - A=B
// the second - the second - A
// the third - C>D etc.
// the fourth - C-D<3 etc.
//now we can make an adequate case statement:
case BitLogic of
0: {00000000b}writeln('all false');
1: {00000001b}writeln('A=B');
2: {00000010b}writeln('A(=true)');
3: {00000011b}writeln('A and A=B');
4: {00000100b}writeln('C>D');
5: {00000101b}writeln('C>D and A=B');
6: {00000110b}writeln('C>D and A');
7: {00000111b}writeln('C>D and A and A=B');
8: {00001000b}writeln('C - D < 3');
9: {00001001b}writeln('C - D < 3 and A=B');
10:{00001010b}writeln('C - D < 3 and A');
11:{00001011b}writeln('C - D < 3 and A and A=B');
12:{00001100b}writeln('C - D < 3 and C>D');
13:{00001101b}writeln('C - D < 3 and C>D and A=B');
14:{00001110b}writeln('C - D < 3 and C>D and A');
15:{00001111b}writeln('C - D < 3 and C>D and A and A=B');
end;
end.
P.S。检查if then else语句的逻辑。有一个错误的决定:你决定,如果不是C&gt; D然后C&lt; D.它是C <= D.我建议你也阅读this SO answer。