错误:类型'int'和'float *'到二元运算符'/'的操作数无效

时间:2014-04-07 15:42:48

标签: c++

Error: invalid operands of types 'int' and 'float*' to binary'operator/'
int *average = new int((num) / data);

显示这行代码。 为什么这样?

float *data;
int num;
int mode;
double average, median;

cout << "How many students were surveyed?  ";
cin >> num;
data = makeArray(num);

float getAverage(float *data, int num)
{
    int *average = new int((data) / num);
    return *average;
}

1 个答案:

答案 0 :(得分:1)

这意味着您要将两种不兼容的类型进行比较。 numdata中的一个是int,另一个是float*。根据您想要的行为

  1. 取消引用指针,就像在*x中指针的任何x一样 2A。您需要将int转换为float floating point division,其结果将转换回int
    2B。您需要将float转换为intinteger division,然后转换回int
  2. <强>更新
    由于您更新了代码,我将指出一个更大的问题;你现在正在泄露记忆。

    我建议你考虑通过值返回你的整数,并可能通过引用或常量引用传递并完全避免指针,但更多的我会建议输入参数中的一些对称性以及const正确性:

    //your code:
    float getAverage( float *data, int sum )
    {    
        //data is a float* and needs to be de-ref'd and casted to int for float but isnt
        int *average = new int( (data) / num );
        //note that now average is a pointer to a newly constructed int that will never be free'd
        return *average;  //because you return it here, where the value will then be implicily converted to a float and be mostly worthless.
    }
    
    // In both suggestions I will use symmetric types, I will not introduce dynamic memory and I will use floating point division for maximal accuracy.
    
    // Suggestion one use Const References
    float getAverage( const float &data, const int &num)
    {
        float result = data / (float) num;
        return result;
    }
    
    // Suggestion two use pointers to constants
    float getAverage( const float *data, const int *num )
    {
        float result = (*data) / float(*num);
        return result;
    }
    
    // Suggestion three pass by value since primitives are cheap
    float getAverage( float data, int num)
    {
        float result = data / (float) num;
        return result;
    }