prolog - 将二进制转换为十进制谓词
问题描述
convertBinToDec(B,D):- atom_number(S,B),
atom_length(S,L),
sub_atom(S, 0, 1, After,S1),
atom_number(S1,N),
L1 is L-1,
sub_atom(S, 1,L1, After ,S2),
atom_number(S2,B2),
convertBinToDec(B2,D1),
D is D1+((2*N)**L1).
convertBinToDec(0,0).
convertBinToDec(1,1).
谓词接受 B ,它是整数形式的二进制数,应该返回 D 其对应的十进制形式,对不起,我对声明性编程语言还是新手,但我不知道为什么我上面的代码总是给出错误,我觉得有问题带有基本情况也不允许使用 prolog 库
解决方案
Given that Prolog supports expressing binary numbers using the 0b
prefix, e.g. 0b10011101
, you can use the standard number_codes/2
predicate to perform the conversion:
convert_binary_to_decimal(Binary, Decimal) :-
number_codes(Binary, Codes),
number_codes(Decimal, [0'0, 0'b| Codes]).
Sample call:
| ?- convert_binary_to_decimal(10011101, Decimal).
Decimal = 157
yes
Verify the result:
| ?- Decimal is 0b10011101.
Decimal = 157
yes
推荐阅读
- r - 如何在 R 中创建以下函数?
- xampp - 我在哪里可以将我的网站文件夹粘贴到 Ubuntu XAMPP 中以访问本地主机服务器?
- elasticsearch - 在 Elasticsearch 搜索结果中跳过字段中的重复项
- flutter - 如何在颤动中制作 Windows 通知?
- python - 来自两列 DataFrame 的 Pandas Series 产生一系列 NaN
- rust - 如何将项目从函数参数推送到函数参数的向量 - 不同的生命周期问题
- python - Is there a way to call multiple get and post requests in a flask appfrom an IOS app
- javascript - getting undefined for a function used in another function
- javascript - 如何从 url 查询字符串,javascript 中获取关联数组
- go - 我如何等待beego中的goroutines终止