C 罗马数字到十进制
试图实现一个非常简单的罗马数字到十进制的转换器,但似乎无法找到一种方法让程序在字符串中有任何非罗马数字字符时返回-1。这就是我目前所拥有的C 罗马数字到十进制,c,C,试图实现一个非常简单的罗马数字到十进制的转换器,但似乎无法找到一种方法让程序在字符串中有任何非罗马数字字符时返回-1。这就是我目前所拥有的 #include <stdio.h> #include <ctype.h> int convertFromRoman(const char *s) { int i = 0; int total = 0; while (s[i] != '\0') { if (isalpha(s[i]) == 0) { r
#include <stdio.h>
#include <ctype.h>
int convertFromRoman(const char *s)
{
int i = 0;
int total = 0;
while (s[i] != '\0') {
if (isalpha(s[i]) == 0) {
return -1;
}
if (toupper(s[i]) == 'I') {
total += 1;
}
if (toupper(s[i]) == 'V') {
total += 5;
}
if (toupper(s[i]) == 'X') {
total += 10;
}
if (toupper(s[i]) == 'L') {
total += 50;
}
if (toupper(s[i]) == 'C') {
total += 100;
}
if (toupper(s[i]) == 'D') {
total += 500;
}
if (toupper(s[i]) == 'M') {
total += 1000;
} else {
return -1;
}
i++;
}
if (total == 0) {
return -1;
}
return total;
}
int main()
{
printf("%d\n", convertFromRoman("XVII"));
printf("%d\n", convertFromRoman("ABC"));
}
#包括
#包括
int convertfroman(常量字符*s)
{
int i=0;
int-total=0;
而(s[i]!='\0'){
if(isalpha(s[i])==0){
返回-1;
}
if(toupper(s[i])=='i'){
总数+=1;
}
如果(toupper(s[i])=='V'){
总数+=5;
}
如果(toupper(s[i])=='X'){
总数+=10;
}
如果(toupper(s[i])=='L'){
总数+=50;
}
如果(toupper(s[i])=='C'){
总数+=100;
}
如果(toupper(s[i])=='D'){
总数+=500;
}
如果(toupper(s[i])=='M'){
总数+=1000;
}否则{
返回-1;
}
i++;
}
如果(总计==0){
返回-1;
}
返回总数;
}
int main()
{
printf(“%d\n”,convertFromRoman(“XVII”);
printf(“%d\n”,convertFromRoman(“ABC”);
}
第一个应该返回17,第二个应该返回-1。然而,它们都返回-1,但是如果我删除else语句,第一个返回17,第二个返回100
非常感谢您的帮助。将if()
if()
if()else
更改为if()
else if()
else if()
else
if (toupper(s[i]) == 'I') {
total += 1;
}
else if (toupper(s[i]) == 'V') {
total += 5;
}
else if (toupper(s[i]) == 'X') {
total += 10;
}
....
else if (toupper(s[i]) == 'M') {
total += 1000;
} else {
return -1;
}
不是一个真正的答案,只是一点有趣的/另类的看待问题的方式。如果您不考虑订购,只需添加“数字”值,它就解决了问题
我们不帮你解决家庭作业。把你的第一行作为作业可能不是个好主意,谢谢你的评论@CharlieFish。没有要求任何人去解决它!我只是想就我遗漏的内容寻求一些建议/参考一些文档。只是把作业放在那里,所以我没有得到一个完整的答案,因为这不是一个好的学习方式!如果,请使用
else。(但是您的逻辑有错误的“IV”结果)您应该返回0代码>来自main
btw.(如果不使用args,技术上使用int main(void)
。@RastaJedi是!如果你想要OP,你可以使用switch(touper(s[i]))
让事情变得简单一点。@RastaJedi OP的代码有很多潜在的改进。对我来说,我会做一些事情。OP在if
else if
else
方面遇到了问题,因此本文的回答重点在于此。顺便说一句,它应该是switch(toupper((unsigned char)s[i])
以避免UB应该s[i]
是否定的;很漂亮。很高兴知道。。。我只是很快打开了这个人,看到原型是inttoupper(intc)“代码>,但我想很多处理字符的函数也会将它们指定为int
,不是吗?”RastaJedi C11dr 7.4讨论了字符处理函数,包括isalpha()
,toupper()
,等等。“在所有情况下,参数均为int
,其值应表示为无符号字符
,或应等于宏EOF
的值。如果参数有任何其他值,则行为是未定义的。“这就是我建议使用(unsigned char)
强制转换的原因。是的,我现在在我的人身上看到了它,它说的是与此相同的话,我只是一时忘记了,甚至像strchr()这样的东西
或者一些需要字符值的东西的原型中也有int
。scanf()
如果你试图使用int参数,为什么会抱怨,但它不会反过来?这就是默认arg促销的工作方式吗?)太糟糕了,我无法编辑我的原始注释:P。
char *romanNumerals = "IVXLCDM";
int values[] = { 1, 5, 10, 50, 100, 500, 1000 };
int convertFromRoman(const char *s) {
int val = 0;
for (int i = 0; s[i]; i++) {
char *idx;
if (NULL == (idx = strchr(romanNumerals, toupper(s[i])))) {
return -1;
}
val += values[idx - romanNumerals];
}
return val;
}