cmath std :: pow函数在分配给变量时给出错误的值?

时间:2013-12-24 07:27:02

标签: c++ c++11 pow cmath

下面的方法是跟踪特定数字从不同数字组的分组中出现的次数

void build_prob_distro(const std::vector<Foo>& num_sets, std::map<int, int>& prob_distro){
    int key;
    Foo cur_foo;

    for(unsigned int foo_num = 0; foo_num<num_sets.size(); foo_num++){
        cur_foo = num_sets.at(foo_num);
        key = 0;
        int val;
        for(int cur_foo_num=0; cur_foo_num<cur_foo.get_foo_length(); cur_foo_num++){
            std::cout << cur_foo.get_num_at(cur_foo_num)*std::pow(10, cur_foo.get_foo_length()-cur_foo_num-1) << std::endl;
            val = cur_foo.get_num_at(cur_foo_num)*std::pow(10, cur_foo.get_foo_length()-cur_foo_num-1);
            std::cout << val << std::endl;
            key = key + cur_foo.get_num_at(cur_foo_num)*std::pow(10, cur_foo.get_foo_length()-cur_foo_num-1);
        }

        prob_distro[key] += 1;
    }
}

我遇到的问题是当我使用std :: pow()方法计算我的地图的键值时,超过100的任何一个都被-1关闭(即100变为99,103变为102等。 )。当我使用std :: cout打印出计算结果是正确的,但是一旦我将值赋给int变量,它就会得到-1错误。我一遍又一遍地查看代码,并没有看到任何问题。关于可能导致此问题的原因和原因的任何建议?

我不相信foo类对于这个例子/问题太重要了,但我会发布它,以防它实际上是某些问题的原因。

//Foo.h
#ifndef FOO_H
#define FOO_H

#include <string>
#include <vector>

class Foo
{
    public:
        Foo();
        Foo(const std::vector<int>& nums);
        int get_num_at(int pos) const;
        int get_foo_length() const;
        std::string to_string() const;
    private:
        std::vector<int> nums;

};

#endif // Foo_H


//Foo.cpp
#include "Foo.h"

#include <string>

Foo::Foo(const std::vector<int>& nums){
    for(int i=0; i<nums.size(); i++){
        this->nums.push_back(nums.at(i));
    }
}

Foo::Foo(){}


/*       SETTERS & GETTERS           */

int Foo::get_num_at(int pos) const{
    if(nums.size() != 0){
        return nums[pos];
    }

    return -1;
}

int Foo::get_foo_length() const{
    return nums.size();
}

/*       END SETTERS & GETTERS         */


std::string Foo::to_string() const{}
编辑:我知道有些人会立即指出在矢量中使用比Foo类更简单的东西,但我还有其他功能,我需要将每个功能集合在一起,所以这是我能想出的最好的方法来保持我的相关的代码在一起,并允许它代表我感兴趣的任何长度整数值(即foo可以表示1,就像它可以表示10000一样容易)。

2 个答案:

答案 0 :(得分:1)

你可能会得到四舍五入的错误,

所以,您可以尝试std::lround

key += cur_foo.get_num_at(cur_foo_num) * std::lround(std::pow(10, cur_foo.get_foo_length() - cur_foo_num - 1));

或编写您自己的pow_int函数以避免使用float

constexpr int pow_int(int x, unsigned int n)
{
    // x ** (2n + 1) == ((x * x) ** n) * x
    // x ** 2n == (x * x) ** n
    // x ** 0 == 1
    return (((n >> 1) == 0) ? 1 : pow_int(x * x, n >> 1)) * (((n & 1) == 0) ? 1 : x);
}

或(线性版)

int pow_int(int x, unsigned int n)
{
    int res = 1;

    for (unsigned int i = 0; i != n; ++i) {
        res *= x;
    }
    return res;
}

答案 1 :(得分:0)

尝试

key = key + cur_foo.get_num_at(cur_foo_num)*std::pow(10, cur_foo.get_foo_length()-cur_foo_num-1) + 0.5;