将罗马数字转换为Int-输出错误-为什么? [英] Converting Roman Numerals to Int - Getting the Wrong Output - Why?

查看:87
本文介绍了将罗马数字转换为Int-输出错误-为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码.首先,我想说的是,我一直在做实验,因此,如果您在这里和那里看到不必要的变量,这就是原因.但是我代码的主要部分是我的类romanType中的十进制函数.当我输入某些罗马数字时,我没有得到想要的确切数字,并且可能在我的if/else语句中的逻辑中.

Here is my code. First, I want to say, I have been experimenting, so if you see unnecessary variables here and there, that's why. But the main part of my code is in the function decimal in my class romanType. When I input certain roman numerals, I am not getting the exact numbers I want and it might be in my logic somewhere in my if/else statements.

顺便说明如何遍历字符串-我通过反向遍历来实现.我从字符串的最开始到字符串的最开始,我认为使用罗马数字更容易.顺便说一句,我还创建了一个枚举类型,以便可以比较罗马数字,看哪个较小,哪个更大等.然后,我使用了一个映射图来比较枚举值和char值.

By the way, to show how I traverse the string - I do it by reverse traversing. I go from the very end of the string to the very beginning of the string, which I think is easier with roman numerals. By the way, I also made an enum type so I could compare the roman numerals seeing which one is lesser, which one is greater etc. Then I used a map to be able to compare the enum values with the char value.

问题在于:例如,当我输入CCC时,我得到的是290,而不是300.如果您知道我的逻辑有什么问题,我将不胜感激!谢谢.

So the problem: For instance, when I type in CCC, I get 290 instead of 300. If you know what is wrong in my logic, I would greatly appreciate that! Thank you.

此外,我对编程还很陌生,将不胜感激任何编写样式技巧或任何我可以学习的有关类等的知识,而我在编写此代码时错过了这些知识?请让我知道什么是最好的.谢谢你.

Furthermore, I am quite new to programming and would greatly appreciate any stylistic tips or anything I can learn about classes etc that I missed in writing this code? Please let me know what is best. Thank you.

#include <iostream>
#include <string>
#include <map>

using namespace std;

class romanType {
string numeral;
int k;
 public:
romanType();
void rnumeral (string b) {numeral = b;}

int decimal(string num, char b, int temp) {
    num = "";


    enum RomanNumerals {I, V, X, L, C, D, M };

    map<char, RomanNumerals> m;

    m['I'] = I;
    m['V'] = V;
    m['X'] = X;
    m['L'] = L;
    m['C'] = C;
    m['D'] = D;
    m['M'] = M;


    RomanNumerals roman1;
    RomanNumerals roman2;


    cout << "Please type in your roman numeral:" ;

    cin >> num;

    for (int i =0; i <num.length()-1; i++){

    }

for(long i = num.length()-1; i>=0; i--)

{
b = num[i];
if (islower(b)) b=toupper(b);

roman1 = m[num[i]];
roman2 = m[num[i-1]];

switch(b){


            case 'I':
                    if(num[i] == num.length()-1){

                            temp += 1;
                            }
                        break;

            case 'V':

                if(roman1 > roman2){
                        temp += 4;
                        continue;
                        }

                else {
                    temp += 5;

                }

                break;


            case 'X':

                if(roman1 > roman2){
                    temp += 9;
                    continue;
                    }

            else {
                temp += 10;
                }

                break;

            case 'L' :

                if(roman1 > roman2){
                        temp += 40;
                        continue;
                    }

                else {
                    temp += 50;
                    }
                break;

            case 'C':

            if(roman1 > roman2){
                temp += 90;
                continue;
            }

            else {
                temp += 100;
            }

                break;

            case 'D' :
            if(roman1 > roman2){
                temp += 400;
                continue;
                }

            else {
                temp += 500;
                }
                break;

            case 'M':
            if(roman1 > roman2){
                temp += 900;
                continue;
                }

            else {
                temp += 1000;
                }
            break;

        }

    }


    return temp;
}
};

romanType::romanType () {
numeral = "";
}


int main() {
string k = "";
char b = ' ';
int temp = 0;

romanType type;
type.rnumeral(k);

int c = type.decimal(k, b, temp);

cout << c;


return 0;
}

_____________________________________________________________________________

_____________________________________________________________________________

我找到了解决问题的方法.这是我的新代码:

I found the solution to my problem. Here is my new code:

#include <iostream>
#include <string>
#include <map>

using namespace std;

string acceptRN();



class romanType {

string numeral;
int temp2;
int l;
// VARIABLES
public:

romanType();
//DEFAULT CONSTRUCTOR


void getRnumeral (string b)
    {
        numeral = b;
    }
//SETTER

void decimal(string num, int temp, char b) {

    num = numeral;

    enum RomanNumerals {I, V, X, L, C, D, M };

    map<char, RomanNumerals> m;

    m['I'] = I;
    m['V'] = V;
    m['X'] = X;
    m['L'] = L;
    m['C'] = C;
    m['D'] = D;
    m['M'] = M;


    RomanNumerals roman1;
    RomanNumerals roman2;
    RomanNumerals roman3;





for(long i = num.length()-1; i>=0; i--)

{
b = num[i];
if (islower(b)) b=toupper(b);

roman1 = m[num[i]];
roman2 = m[num[i-1]];
roman3 = m[num[i+1]];

switch(b){


        case 'I':

        if( roman3 > roman1 && i != num.length()-1){
            continue;
        }

        else {
                temp += 1;
                        break;
        }



            case 'V':

                if(roman1 > roman2 && i != 0){
                        temp += 4;
                        continue;
                        }

                else {
                    temp += 5;

                }

                break;


            case 'X':

        if( roman3 > roman1 && i != num.length()-1)
            continue;

        if(roman1 > roman2 && i!= 0){
            temp += 9;
            continue;
                    }

            else {
                temp += 10;
                }

                break;

            case 'L' :

                if(roman1 > roman2 && i!= 0){

                        temp += 40;
                        continue;
                    }



                else {
                    temp += 50;
                    }
                break;

            case 'C':

            if( roman3 > roman1 && i != num.length()-1)
                continue;

            if(roman2 == X && i!= 0){
                temp += 90;
                continue;
            }

            else {
                temp += 100;
            }

                break;

            case 'D' :
            if(roman2 == C && i!= 0){
                temp += 400;
                continue;
                }

            else {
                temp += 500;
                }
                break;

            case 'M':
            if(roman2 == C && i!= 0){
                temp += 900;
                continue;
                }

            else {
                temp += 1000;
                }
            break;


        }

    }
 temp2 = temp;
}

void showDecimal() {

cout << "Here is your roman numeral in decimal format:";
cout << temp2 << " \n \n \n";
}

};

romanType::romanType () {
numeral = "";



}


int main() {
string k = acceptRN();
int m = 0;
char l= ' ';

romanType type;
type.getRnumeral(k);
type.decimal(k, m, l);
type.showDecimal();


return 0;
}

string acceptRN(){
string num = "";
cout << "Please type in your roman numeral:" ;
cin >> num;

return num;

}

推荐答案

当我从注释中完成内容并稍微调整了代码后,我得到了:

When I done the stuff from my comment and tweaked your code a bit I got this:

//---------------------------------------------------------------------------
      int  roman_ix[256]={-1};
const int  roman_val[]={ 1 , 5 ,10 ,50 ,100,500,1000,0};
const char roman_chr[]={'I','V','X','L','C','D', 'M',0};
//---------------------------------------------------------------------------
int roman2int(char *s)
    {
    int i,x=0,v=0,v0;
    // init table (just once)
    if (roman_ix[0]<0)
        {
        for (i=0;i<256;i++) roman_ix[i]=0;
        for (i=0;roman_chr[i];i++) roman_ix[roman_chr[i]]=i;
        }
    // find end of string
    for (i=0;s[i];i++);
    // proccess string in reverse
    for (i--;i>=0;i--)
        {
        v0=v;                        // remember last digit
        v=roman_val[roman_ix[s[i]]]; // new digit
        if (!v) break;               // stop on non supported character
        if (v0>v) x-=v; else x+=v;   // add or sub
        }
    return x;
    }
//---------------------------------------------------------------------------

我对这些进行了测试:

1776 1776 MDCCLXXVI
1954 1954 MCMLIV
1990 1990 MCMXC
2014 2014 MMXIV
 300  300 CCC

第一个数字是从字符串转换而来的,第二个是它应该是的,最后一个是罗马字符串.

first number is converted from string, second is what it should be and last is the roman string.

如果256个条目表太大,则可以将其缩小到A-Z范围,该范围显着较小,但是需要在代码中再减去一个.也可以对其进行硬编码以摆脱初始化:

If 256 entry table is too big you can shrink it to range A-Z which is significantly smaller but that require one more substraction in the code. It can be also hardcoded to get rid of the initialization:

//---------------------------------------------------------------------------
int roman2int(char *s)
    {
    // init
    int i,x=0,v=0,v0;       // A  B    C    D  E  F  G  H  I  J  K   L     M  N  O  P  Q  R  S  T  U  V  W   X  Y  Z
    const int val['Z'-'A'+1]={ 0, 0, 100, 500, 0, 0, 0, 0, 1, 0, 0, 50, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 10, 0, 0 };
    // find end of string
    for (i=0;s[i];i++);
    // process string in reverse
    for (i--;i>=0;i--)
        {
        if ((s[i]<'A')||(s[i]>'Z')) break; // stop on non supported character
        v0=v; v=val[s[i]-'A'];
        if (v0>v) x-=v; else x+=v;
        }
    return x;
    }
//---------------------------------------------------------------------------

当我摆脱了您的temproman1,roman2switch if/else条件,并且代码从第一次编译起就开始工作了...我假设您对它们做了一些可疑的事情(如果在if中迷路了,/else组合缺少一些边缘情况).

As I got rid of your temp and roman1,roman2 and the switch if/else conditions and the code worked from the first compilation ... I am assuming that you are doing something fishy with them (got lost in the if/else combinations missing some edge case).

这篇关于将罗马数字转换为Int-输出错误-为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆