【发布时间】:2018-05-17 17:32:17
【问题描述】:
我对 C++ 比较陌生,并且在 Java 方面有一些关于类和函数的经验,但现在非常多,所以这个程序给我带来了一些问题。下面是我拥有的代码,对我来说,一切似乎都是正确的,即使我将“num”设置为 0,它总是打印出“-858993460”。
这是我的头文件:
#include <string>
using namespace std;
class romanType
{
public:
void setRoman(string n);
void romanToPositiveInteger();
void printPositiveInteger() const;
romanType();
romanType(string n);
void printNum();
private:
string romanString;
int num;
};
这是我的实现文件:
#include "stdafx.h"
#include <iostream>
#include <string>
#include "romanType.h"
using namespace std;
int value(char num) {
if (num == 'I')
return 1;
if (num == 'V')
return 5;
if (num == 'X')
return 10;
if (num == 'L')
return 50;
if (num == 'C')
return 100;
if (num == 'D')
return 500;
if (num == 'M')
return 1000;
return -1;
}
void romanType::setRoman(string n) {
romanString = n;
}
void romanType::romanToPositiveInteger() {
num = 0;
for (int i = 0; i < romanString.length(); i++)
{
// Getting value of symbol s[i]
int s1 = value(romanString[i]);
if (i + 1 < romanString.length())
{
// Getting value of symbol s[i+1]
int s2 = value(romanString[i + 1]);
// Comparing both values
if (s1 >= s2)
{
// Value of current symbol is greater
// or equal to the next symbol
num = num + s1;
}
else
{
num = num + s2 - s1;
i++; // Value of current symbol is
// less than the next symbol
}
}
else
{
num = num + s1;
i++;
}
}
}
void romanType::printPositiveInteger() const {
cout << num << endl;
}
romanType::romanType(string n) {
romanString = n;
}
romanType::romanType() {
}
void romanType::printNum() {
cout << num << endl;
}
这是我的主文件:
#include "stdafx.h"
//Main program
#include <iostream>
#include <string>
#include "romanType.h"
using namespace std;
int main()
{
romanType roman;
string romanString;
while (romanString != "EXIT") {
cout << "Enter a roman number: ";
cin >> romanString;
roman.printNum();
roman.setRoman(romanString);
cout << "The equivalent of the Roman numeral "
<< romanString << " is ";
roman.printPositiveInteger();
cout << endl;
cout << endl;
}
//Pause the program
std::cout << "\n\n---------------------------------\n";
system("pause");
//Exit the program
return EXIT_SUCCESS;
}
正如我之前所说,我目前在输出部分受到阻碍,但由于我是新手,而且这段代码很可能很糟糕,所以我接受任何批评。我今天工作很忙,直到第二天才能实施任何建议,但我会尽快回复任何有解决方案的人!提前感谢您的帮助:)
【问题讨论】:
-
看起来像堆栈上未初始化的变量。 0xcc 是微软调试版本中的一个特殊值。 stackoverflow.com/questions/127386/…
-
在主程序的输出中它可以识别romanString字符串的输入,并且我在函数的开头将num设置为0,那么还有什么问题呢?我也想过这个问题,但不确定如何解决或问题出在哪里
-
我现在回去,确保一切都已初始化,看看是否修复它,如果修复它,我会报告!
-
@H.Earley 你也可以看看答案部分。 ;-)
-
我建议你学会自己使用调试器。调试器是必不可少的工具。通过学习正确的调试,您将节省许多时间。我仍然几乎每天都在调试,自 1980 年代初以来我已经编程/专业编写了超过一百万行 c++ 代码。
标签: c++ function class output roman-numerals