序言将数字转换为罗马数字

序言将数字转换为罗马数字

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

问题描述

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

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).

推荐答案

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

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).

您可以像这样使用它:


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


?- 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.

要像L = "III"一样紧凑地获取答案,请使用:- set_prolog_flag(double_quotes,chars).参见此答案以了解更多信息.

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

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

08-29 03:31