1
/* MAIN PROGRAM */

main:- welcome.

welcome:-
    write('************************************************'),nl,
    write('*   Welcome to my Simple Calculator   *'),nl,
    write('************************************************'),nl,nl,
    write('For every input you enter, please followed by a full stop[.]'),
    numbers.

numbers:-
    nl,nl,write('First number: '),
    read(FIRST),nl,
    write('Second number: '),
    read(SECOND),nl,
    operation.

operation:-
    nl,write('[1]- Addition.'), nl,
    nl,write('[2]- Subtraction.'),nl,
    nl,write('[3]- Multiplication.'),nl,
    nl,write('[4]- Division.'),nl,
    nl,write('[5]- Exit.'),nl,
    nl,write(':>'),
    read(ANS1),nl,
    set_op(ANS1).

set_op(1):-
    write(FIRST),write(SECOND),
    SUM is FIRST + SECOND,
    write(SUM).

我在做一个简单的计算器程序时遇到了麻烦。由于某种原因,它只会在被调用时传递变量的地址而不是值。如果有人能指出我的单据,我将不胜感激。谢谢你。

4

1 回答 1

1

Prolog 中的变量不是全局的。所以FIRSTand SECONDin yourset_op本地范围的。因此,您的FIRST和是与谓词中的变量不同的变量。SECONDset_op/1numbers/0

在声明性编程语言中,通常函数/谓词/...的结果仅取决于传递的参数。尽管在 Prolog 中有一些方法可以表示“全局状态”,例如不可回溯的存储,但通常认为应用该原则更好,因此不实现某种全局状态。

您需要传递变量,例如:

numbers :-
    nl,nl,write('First number: '),
    read(First),nl,
    write('Second number: '),
    read(Second),nl,
    operation(First, Second).

operation(First, Second) :-
    nl,write('[1]- Addition.'), nl,
    nl,write('[2]- Subtraction.'),nl,
    nl,write('[3]- Multiplication.'),nl,
    nl,write('[4]- Division.'),nl,
    nl,write('[5]- Exit.'),nl,
    nl,write(':>'),
    read(Op),nl,
    write(First), write(Second),
    set_op(Op, First, Second).

set_op(1, First, Second) :-
    Sum is First + Second,
    write(Sum).
于 2020-01-05T15:50:46.723 回答