c++ - C++ 程序错误

标签 c++

我目前正在上 C++ 类(class),请多多包涵。我不是要你解决我的作业,只是简单地帮我弄清楚我忽略了什么 我正在将用户输入的罗马数字转换为十进制数,然后显示该数字。我还没有完成我的转换功能。现在,我只是将数字转换为数字并将它们相加(尚未考虑订单)。每当我运行程序时,我总是得到一个 0 而不是正确的数字。这是我的头文件代码:

class romanType
    {
    public:
        void setNumeral(string);
        string getNumeral();
        double convertToNumber();
        double printNumber();
    private:
        string input;
        double num;
    };

void romanType::setNumeral(string s)
{
    string input = s;
}

string romanType::getNumeral()
{
    return input;
}

double romanType::convertToNumber()
{
    num = 0;
    for(int i = 0; i < input.length(); i++)
    {
        switch (input.at(i))
        {
        case 'M':
            num += 1000;
            break;
        case 'D':
            num += 500;
            break;
        case 'C':
            num += 100;
            break;
        case 'L':
            num += 50;
            break;
        case 'X':
            num += 10;
            break;
        case 'V':
            num += 5;
            break;
        case 'I':
            num += 1;
            break;
        }
    }
    return num;
}

double romanType::printNumber()
{
    return num;
}

这是我的cpp文件代码:

#include "stdafx.h"
#include "romanType.h"
#include <string>
#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    romanType roman;
    string input;
    string output;
    double number = 0;
    cout << "Enter a Roman numeral." << endl;
    cin >> input;
    roman.setNumeral(input);
    number = roman.convertToNumber();
    cout << number << endl;

    system("pause");
    return 0;
}

最佳答案

在你的 romanType::setNumeral() 中删除输入前的“string”字:

错了:

 romanType::setNumeral(string s)
 {
      string input=s;
 }

对:

romanType::setNumeral(string s)
{
    input=s;
}

在错误的示例中,您使用同名的局部变量隐藏了您的成员变量。

关于c++ - C++ 程序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28073181/

相关文章:

非类 typedef 的 C++ 前向声明

c++ - 如何判断 std::vector 是否调整了自身大小,以及如何解释指向 vector 内值的指针不再有效?

c++ - 在 DDD 中显示 STL 类

c++ - 棘手的回调实现(C++)

c++ - 用于创建唯一命名的 OpenMP 临界区的宏?

从 double 进行以 10 为底的有效 + 指数计算的 C++ 函数

c++ - 如何在 Linux 上初始化共享库

c++ - 如果我没有为其相应命令声明消息映射条目,如何阻止 MFC 禁用我的控件?

C++ - 对象作为参数中的变量

c++ - 如何将文本文件读入双端队列