C ++中的罗马数字输出总是" -858993460",不确定为什么?

时间:2018-05-17 17:32:18

标签: c++ function class output roman-numerals

我对C ++比较陌生,并且在Java和类和函数方面有一些经验,但现在非常多,所以这个程序给了我一些问题。下面是我的代码,现在对我来说似乎一切,即使我已经设置了#34; 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;
}

正如我之前所说的,我目前在输出部分处于阻碍状态,但由于我是新手并且这段代码很可能很可怕,我接受任何批评。今天我将非常忙于工作,直到第二天才能实施任何建议,但我会尽快回复任何有解决方案的人!在此先感谢您的任何帮助:)

1 个答案:

答案 0 :(得分:3)

您需要在roman.setRoman(romanString);roman.printPositiveInteger();

之间的某个时刻致电library(tidyverse) library(broom) mtcars$cyl2 <- factor(mtcars$cyl, levels = c(4,6,8), labels = paste("Cyl:", unique(mtcars$cyl))) mod2 <- lm(mpg ~ cyl2 * factor(am), data = mtcars) mod2 %>% tidy %>% as_tibble %>% filter(term %>% str_detect("\\w{1}:\\w{1}")) %>% pull(estimate) [1] -3.733333 -4.825000