我正在尝试编写一个将罗马数字转换为整数的程序,但其编译输出以下错误:
Line 65: Char 5: error: conflicting types for 'main'
int main(int argc, char *argv[]) {
^
Line 47: Char 5: note: previous definition is here
int main()
^
1 error generated.
这里有一些我的代码:
class Solution {
public:
int value(char r){
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
}
int romanToInt(string& s) {
int ret = 0;
for (int i = 0; i < s.length(); i++) {
int s1 = value(s[i]);
if (i + 1 < s.length()) {
int s2 = value(s[i + 1]);
if (s1 >= s2) {
ret = ret + s1;
}
else {
ret = ret + s2 - s1;
i++;
}
}
else {
ret = ret + s1;
}
}
return ret;
}
};
int main()
{
Solution m;
string str = "III";
cout << "Integer form of Roman Numeral is " << m.romanToInt(str) << endl;
return 0;
}
方法
value()
逐个字母读取带有罗马数字的字符串并识别每个字母的值。main()
功能需要做一些改变才能完成这项任务,但我对如何去做有点困惑。
您可能已经定义了函数
int main()
两次。考虑到错误信息
Line 65: Char 5: error: conflicting types for 'main'
int main(int argc, char *argv[]) {
^
Line 47: Char 5: note: previous definition is here
int main()
^
1 error generated.
说第 65 行有错误,而你的代码长度不到 60 行,我认为代码比这里复制的代码多。
main()
函数定义和你的错误信息您的错误消息表明
main()
函数有两个相互冲突的定义。例如,如果您在文件顶部声明一个 main()
函数,如下所示:
int main(int argc, char *argv[]);
但是你使用你的
main()
函数定义:
int main()
{
Solution m;
string str = "III";
cout << "Integer form of Roman Numeral is " << m.romanToInt(str) << endl;
return 0;
}
编译输出一个类似于你的错误。
你的代码是正确的,我只做了以下修改:
string str
变量(通过指令std::cin
)以简化测试main()
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++
// I have also added the following #include to your code
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++
#include <iostream>
#include <string>
using namespace std;
// correct declaration of main()
int main();
/*+++++++++++++++++++++++++++++++++++++++
Your code for Class Solution is correct
+++++++++++++++++++++++++++++++++++++++*/
class Solution {
public:
int value(char r){
if (r == 'I')
return 1;
if (r == 'V')
return 5;
if (r == 'X')
return 10;
if (r == 'L')
return 50;
if (r == 'C')
return 100;
if (r == 'D')
return 500;
if (r == 'M')
return 1000;
return -1;
}
int romanToInt(string& s) {
int ret = 0;
for (int i = 0; i < s.length(); i++) {
int s1 = value(s[i]);
if (i + 1 < s.length()) {
int s2 = value(s[i + 1]);
if (s1 >= s2) {
ret = ret + s1;
}
else {
ret = ret + s2 - s1;
i++;
}
}
else {
ret = ret + s1;
}
}
return ret;
}
};
int main()
{
Solution m;
string str;
cout << "Insert a Roman Number: ";
cin >> str;
cout << "Integer form of Roman Numeral is " << m.romanToInt(str) << endl;
return 0;
}
要在 Linux 系统(安装了 g++ 编译器)中编译之前的程序,将其保存在名为
solution.cpp
的文件中,将文件夹更改为包含该文件的文件夹并编译它:
> cd /path/to/file-source
> g++ solution.cpp -o solution
执行程序使用:
> ./solution
代码执行的输出为:
Insert a Roman Number: III
Integer form of Roman Numeral is 3