我正在尝试编写一个程序,将罗马数字转换为整数,但其编译输出以下错误:
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;
}
编译输出一个类似于您的错误,因为您的定义缺少参数int argc
,char *argv[]
。
正确的代码你的代码是正确的,我只做了以下修改:
- 增加了通过键盘插入
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系统中编译和执行程序
要在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