#include<stdio.h>
#include<string.h>
int main()
{
char ch[5];
int i = 0;
while(scanf("%s",&ch) != EOF)
{
i++;
int len = strlen(ch);
if(len == 1)
{
if(strcmp(ch,"I") == 0) printf("Case %d: 1\n",i);
else if(strcmp(ch,"V") == 0) printf("Case %d: 5\n",i);
else printf("Case %d: 10\n",i);
}
else if(len == 2)
{
if(strcmp(ch,"II") == 0) printf("Case %d: 2\n",i);
else if(strcmp(ch,"IV") == 0) printf("Case %d: 4\n",i);
else if(strcmp(ch,"VI") == 0) printf("Case %d: 6\n",i);
else if(strcmp(ch,"IX") == 0) printf("Case %d: 9\n",i);
else printf("Case %d: 11\n",i);
}
else if(len == 3)
{
if(strcmp(ch,"III") == 0) printf("Case %d: 3\n",i);
else if(strcmp(ch,"VII") == 0) printf("Case %d: 7\n",i);
else printf("Case %d: 12\n",i);
}
else printf("Case %d: 8\n",i);
}
return 0;
#include<string.h>
int main()
{
char ch[5];
int i = 0;
while(scanf("%s",&ch) != EOF)
{
i++;
int len = strlen(ch);
if(len == 1)
{
if(strcmp(ch,"I") == 0) printf("Case %d: 1\n",i);
else if(strcmp(ch,"V") == 0) printf("Case %d: 5\n",i);
else printf("Case %d: 10\n",i);
}
else if(len == 2)
{
if(strcmp(ch,"II") == 0) printf("Case %d: 2\n",i);
else if(strcmp(ch,"IV") == 0) printf("Case %d: 4\n",i);
else if(strcmp(ch,"VI") == 0) printf("Case %d: 6\n",i);
else if(strcmp(ch,"IX") == 0) printf("Case %d: 9\n",i);
else printf("Case %d: 11\n",i);
}
else if(len == 3)
{
if(strcmp(ch,"III") == 0) printf("Case %d: 3\n",i);
else if(strcmp(ch,"VII") == 0) printf("Case %d: 7\n",i);
else printf("Case %d: 12\n",i);
}
else printf("Case %d: 8\n",i);
}
return 0;
}
这里要注意的就是strcmp函数的用法了,比较的双方必须都是字符串。
以下是最有代码,用的是映射数组,很简便。
#include<map>
#include<iostream>
#include<string>
using namespace std;
map<string,int>m;
int main()
{
m["I"]=1;
m["II"]=2;
m["III"]=3;
m["IV"]=4;
m["V"]=5;
m["VI"]=6;
m["VII"]=7;
m["VIII"]=8;
m["IX"]=9;
m["X"]=10;
m["XI"]=11;
m["XII"]=12;
string s;
int c=0;
while(cin>>s)
cout<<"Case "<<++c<<": "<<m[s]<<endl;
return 0;
}
本文提供了两种实现将特定罗马数字转换为整数的方法。一种使用传统C语言结构,通过逐字符对比并打印对应数值;另一种则利用C++的映射功能简化流程。这两种方法都针对固定长度的罗马数字进行处理。
879

被折叠的 条评论
为什么被折叠?



