本文介绍了prolog 将数字转换为罗马数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以将整数转换为罗马数字我需要添加一个函数,将整数与罗马数字输入进行比较,并显示它是 try 还是 false,例如:罗马(v,5).真的

toroman(0).托罗曼(N):- N 
解决方案

试着用不同的方式表述问题:写一个语法(dcg) 的问题,以关联整数和表示罗马数字的字符列表.这是一个开始:

:- 使用模块(库(clpfd)).罗马(0)->".罗马(N0)->我",{ 1 #=<N0, N0 #=<3,N1 #= N0-1},罗马(N1).

你可以这样使用它:

?- 短语(罗马(3),L).L =三";错误的.

?- 短语(罗马(N),II").N = 2;错误的.

或者,如果您不知道该问什么,只需问最普遍的问题:

?- 短语(罗马(N),L).N = 0,L = [];N = 1,L = "我" ;N = 2,L = "二" ;N = 3,L =三";错误的.

要像 L = "III" 那样简洁地获得答案,请使用 :- set_prolog_flag(double_quotes,chars). 请参阅 这个答案了解更多.

i have this code that converts integers into roman numeralsi need to add a function that compares an integer with a roman numeral input and show if it's try or false, for example:roman(v,5).true

toroman(0).
toroman(N) :- N < 4, put("I"), M is N - 1, toroman(M).
toroman(N) :- N = 4, put("I"), put("V").
toroman(N) :- N = 5, put("V").
toroman(N) :- N < 9, put("V"), M is N - 5, toroman(M).
toroman(N) :- N = 9, put("I"), put("X").
toroman(N) :- N < 40, put("X"), M is N - 10, toroman(M).
toroman(N) :- N < 50, put("X"), put("L"), M is N - 40, toroman(M).
toroman(N) :- N < 90, put("L"), M is N - 50, toroman(M).
toroman(N) :- N < 100, put("X"), put("C"), M is N - 90, toroman(M).
toroman(N) :- N < 400, put("C"), M is N - 100, toroman(M).
toroman(N) :- N < 500, put("C"), put("D"), M is N - 400, toroman(M).
toroman(N) :- N < 900, put("D"), put("D"), M is N - 500, toroman(M).
toroman(N) :- N < 1000, put("C"), put("M"), M is N - 900, toroman(M).
toroman(N) :- N < 4000, put("M"), M is N - 1000, toroman(M).



roman(N) :- toroman(N).
解决方案

Try to formulate the problem differently: Write a grammar (dcg) to relate an integer and a list of characters denoting roman numerals. Here is a start:

:- use_module(library(clpfd)).

roman(0) --> "".
roman(N0) --> "I", { 1 #=< N0, N0 #=< 3, N1 #= N0-1}, roman(N1).

You can use it like so:

?- phrase(roman(3), L).
L = "III" ;
false.

or

?- phrase(roman(N), "II").
N = 2 ;
false.

or, if you don't know what to ask, simply ask the most general question:

?- phrase(roman(N), L).
N = 0,
L = [] ;
N = 1,
L = "I" ;
N = 2,
L = "II" ;
N = 3,
L = "III" ;
false.

To get answers compactly like L = "III", use :- set_prolog_flag(double_quotes,chars). See this answer for more.

这篇关于prolog 将数字转换为罗马数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 16:20