nyoj484The famouse clock

本文提供了两种实现将特定罗马数字转换为整数的方法。一种使用传统C语言结构,通过逐字符对比并打印对应数值;另一种则利用C++的映射功能简化流程。这两种方法都针对固定长度的罗马数字进行处理。
#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;

}

这里要注意的就是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;
}        

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值