c++ - 程序计算错误,类型转换

标签 c++ function pointers math type-conversion

我制作了一个程序,它接受用户输入的单词,将它们转换为数字,运行计算,然后将它们转换回单词,非常简单,但是我的代码有错误。

每当我尝试输入一百或更高的值时,我得到的输出是“零”。 (很可能意味着我尝试转换的数字是零,而实际上它不应该是零。)

出于这个原因,我认为问题出在计算函数“write_value”中,但是我不确定是什么。

过去几个小时我一直在做这个,所以它可能是我没有看到的小东西,但它可能是几件事,所以与其浪费更多时间,我想我应该把它贴在这里供一些更有经验的人看看。

在此先感谢您的帮助。 ^^

示例输入为: one_hundred_44 + two_hundred_thirty_8

正确的输出: three_hundred_eighty_two

当前输出: 零

当前代码:

using namespace std;

/**
 * Map units digits into words
 * 
 */
string units[] = {
    "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
    "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
    "seventeen", "eighteen", "nineteen"
};

/**
 * Map tens digits into words
 */
string tens[] = {
    "", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"
};

/**
 * Splits a string into components
 * 
 * @param words array for the components (assumed large enough)
 * @param base the string to split
 * @param separator the separator character
 * @return pointer to the first unused element in the array
 */
string* split(string* words, string base, char separator) {
    string* result = words;
    istringstream input(base);
    string token;
    while (getline(input, token, separator)) {
        if (token.length() > 0 && token != "and") {
            if (token == "hundred") {
                *--result += "_hundred";
                *result++;
            } else if (token == "thousand") {
                *--result += "_thousand";
                *result++;
            } else if (token == "million") {
                *--result += "_million";
                *result++;
            } else {
                *result++ = token;
            }
        }
    }
    return result;
}

/**
 * Joins an array of component strings into a single string
 * 
 * @param words pointer to first component
 * @param end pointer to the component beyond the last
 * @param separator the separator character
 * @return the joined string
 */
string join(string* words, string* end, char separator) {
    string result;
    if (words < end) {
        result.append(*words);
        for (string* w = words + 1; w < end; w++) {
            result.append(separator + *w);
        }
    }
    return result;
}

/**
 * Writes number words into an array
 * 
 * @param words array to store the words
 * @param n the number to write
 * @return pointer to the first unused element
 */
string* write_value(string* words, int n) {
    string* result = words;


    int t = (n % 100) / 10;
    int u = (n % 10);

    if (t == 1) { // fixes teens
        t--;
        u += 10;
    }
    if (t) {
        *result++ = tens[t];
    }
    if (u) {
        *result++ = units[u];
    }
    return result;
}

/**
 * Reads an array of number words
 * 
 * @param words the number words to read
 * @param end pointer to the word beyond the last
 * @return the value read
 */
int read_value(string* words, string* end) {
    int result = 0;
    string* w = words;

    for (int i = 1; i < 10; i++) {
        if (*w == tens[i]) {
            result += 10 * i;
            w += 1;
            break;
        }
    }
    for (int i = 1; i < 20; i++) {
        if (*w == units[i]) {
            result += i;
            break;
        }
    }
    return result;
}

/**
 * Writes a number word string
 * 
 * @param n the number to write
 * @return the word string
 */
string Wordnum::write_number(int n) {
    string result;
    string words[20]; 
    string* end;
    if (n == 0) {
        result = "zero";
    } else if (n < 0) {
        end = write_value(words, -n);
        result = "negative_" + join(words, end, '_');
    } else {

        if (n > 100) {
            end = write_value(words, n);
            result = join(words, end, '_') + "hundred_";
        } else if (n > 1000) {
            end = write_value(words, n);
            result = join(words, end, '_') + "thousand_";
        } else if (n > 1000000) {
            end = write_value(words, n);
            result = join(words, end, '_') + "million_";
        }
        end = write_value(words, n);
        result = join(words, end, '_');
    }
    return result;
}

/**
 * Reads a number word string
 * 
 * @param n the string to read
 * @return the value read
 */
int Wordnum::read_number(string n) {
    int result;
    string words[20]; 
    for (int i = 0; i < n.length(); i++) {
        n[i] = tolower(n[i]);
        if (n[i] == '-') n[i] = '_';
    }
    string* end = split(words, n, '_');

    if (end == words || words[0] == "zero") {
        result = 0;
    } else if (words[0] == "negative") {
        result = -read_value(words + 1, end);
    } else {
        result = read_value(words, end);

        for (int i = 0; i < n.length(); i++) {
            if (words[i] == "hundred") {
                result = read_value(words - 1, end) * 100;
                break;
            } else if (words[i] == "thousand") {
                result = read_value(words - 1, end) * 1000;
                break;
            } else if (words[i] == "million") {
                result = read_value(words - 1, end) * 1000000;
                break;
            }
        }
    }
    return result;
}

/**
 * Inserts a Wordnum into an output stream as a word string
 * 
 * @param os the stream to insert into
 * @param n the value to insert
 * @return the modified stream
 */
ostream& operator<<(ostream& os, const Wordnum& n) {
    return os << Wordnum::write_number(n.value_);
}

/**
 * Extracts a Wordnum in word string form from an input stream
 * 
 * @param is the stream to extract from
 * @param n the value to assign
 * @return the modified stream
 */
istream& operator>>(istream& is, Wordnum& n) {
    string text;
    if (is >> text) {
        n.value_ = Wordnum::read_number(text);
    }
    return is;
}

头文件:

 #ifndef WORDNUM_H_
#define WORDNUM_H_

#include <string>
#include <istream>
#include <ostream>

/**
 * A class to read and write numbers in word form
 */

class Wordnum {
public:

    /**
     * Writes a number word string
     * 
     * @param n the number to write
     * @return the word string
     */
    static std::string write_number(int n);

    /**
     * Reads a number word string
     * 
     * @param n the string to read
     * @return the value read
     */
    static int read_number(std::string n);

    /**
     * Creates a new Wordnum for a given value
     * 
     * @param n the value of the number
     */
    Wordnum(int n = 0) {
        value_ = n;
    }

    /**
     * Creates a new Wordnum from a word string
     * 
     * @param n the value of the number
     */
    Wordnum(std::string n) {
        value_ = read_number(n);
    }

    /**
     * Creates a new Wordnum as a copy of another
     * 
     * @param n the value to copy
     */
    Wordnum(const Wordnum& n) {
        value_ = n.value_;
    }

    /**
     * Makes this equivalent to n
     * 
     * @param n the value to copy
     * @return the modified Wordnum
     */
    Wordnum& operator =(const Wordnum& n) {
        value_ = n.value_;
        return *this;
    }

    /**
     * Converts a Wordnum to an int
     * 
     * @return the value as an int
     */
    operator int () const {
        return value_;
    }

    /**
     * Converts a Wordnum to a string
     * 
     * @return the value as a word string
     */
    operator std::string() const {
        return write_number(value_);
    }

    /**
     * Inserts a Wordnum into an output stream as a word string
     * 
     * @param os the stream to insert into
     * @param n the value to insert
     * @return the modified stream
     */
    friend std::ostream& operator <<(std::ostream &os, const Wordnum& n);

    /**
     * Extracts a Wordnum in word string form from an input stream
     * 
     * @param is the stream to extract from
     * @param n the value to assign
     * @return the modified stream
     */
    friend std::istream& operator >>(std::istream &is, Wordnum& n);

    /**
     * Returns sum of n1 and n2
     */
    friend Wordnum operator +(const Wordnum& n1, const Wordnum& n2) {
        return Wordnum(n1.value_ + n2.value_);
    }

    /**
     * Returns difference of n1 and n2
     */
    friend Wordnum operator -(const Wordnum& n1, const Wordnum& n2) {
        return Wordnum(n1.value_ - n2.value_);
    }

    /**
     * Returns product of n1 and n2
     */
    friend Wordnum operator *(const Wordnum& n1, const Wordnum& n2) {
        return Wordnum(n1.value_ * n2.value_);
    }

    /**
     * Returns quotient of n1 and n2
     */
    friend Wordnum operator /(const Wordnum& n1, const Wordnum& n2) {
        return Wordnum(n1.value_ / n2.value_);
    }

private:
    int value_;
};

#endif

最佳答案

将字符转换为整数并不简单。
一个 char*(cstring) 是一个 char 数组, 其中每个元素的大小为一个字节(8 位)

一个整数是 4 个字节(32 位),因此, 正确地从 char 转换为 int 你 必须用 char 填充 4 个字节中的每一个。 换句话说,您需要 4 个字符才能构成一个 int。

好像这还不够,还有一个因素 需要考虑到这一点。 字节顺序 (我会留给你去查)你的 需要考虑系统。

字节顺序决定了您的系统如何存储数据。 例如,在 16 位整数中,您存储数字 2 您的系统可以通过以下两种方式之一存储它:

方式一:00000010 00000000

方式二:00000000 00000010

由于 16 位整数存储在 2 个字节中,因此可以 从右到左或从左到右。 Here 是一张图片。

这是进行字节序检查所必需的代码 从 char* (cstring) 转换为 int (32 位整数)

bool isBigEndian(){
    int a = 1;
    return !((char*)&a)[0];
}

int convertToInt(char *charArr, int len){          //len should be <= 4
    int a = 0;
    if(!isBigEndian())
        for(int i = 0; i < len; i++)
            ((char*)&a)[i] = charArr[i];
    else
        for(int i = 0; i < len; i++)
            ((char*)&a)[3-i] = charArr[i];
    return a;
}

因为代码将适用于大小为 4 或更小的 char* 数组,任何更多都不起作用 因为 int 不能容纳超过 4 个字节。我建议查找 big endian 与 little endian 在查看代码之前,它会更有意义。如果您对这是如何完成的有直觉,您可以转换为常规 int 以外的类型,您可以转换为 Uint16(16 位)或 Uint8(8 位;一次存储一个字符的完美大小;)

我希望你现在已经解决了这个问题,如果没有,希望这对你有所帮助。

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

相关文章:

c++ - 在 Ubuntu 上使用 Eclipse C++ 时的 makefile 问题

C++比较字符串数组元素

postgresql - 为postgresql中的每个更新行调用一个函数

c - 使用 "beep function"与其他命令并行?

C++:指针指向的值发生变化

c++ - 如何返回列表成员 C++ 的空指针?

c - C 中使用数组变量的指针运算

c++ - 在 XCode 中发出未使用的参数警告

c++ - 无法为 vector 的 vector 解析 Eclipse 方法

function - 如何将任意数据类型写入Matlab元胞数组