加法和整数除法的操作数错误?

时间:2018-09-23 03:17:21

标签: c++

这是我的职责。我想知道为什么我不能对两个int变量执行简单的数学运算

int sockMerchant(int n, vector<int> ar) {
int pairs;

for (int i = 1; i <= 100 ; i++) { //for every number ("Color") between 1 and 100
    for (int j = 0; j < n; j++) { //iterate thru array to look for it
        if (ar[j] == i) { //once found,
            for (int k = j; k < n ; k++) { //count how many of that number is there
                if (ar[k] == i) {
                    int count;
                    count++;
                }
            }
        count = (count/2);
        pairs = (pairs+count);
        }
    }
}
return pairs;
}

这是收到的错误:

solution.cc: In function ‘int sockMerchant(int, std::vector<int>)’:
solution.cc:20:27: error: invalid operands of types ‘<unresolved overloaded 
function type>’ and ‘int’ to binary ‘operator/’
         count = (count/2);
                  ~~~~~^~
solution.cc:21:27: error: invalid operands of types ‘int’ and ‘<unresolved 
overloaded function type>’ to binary ‘operator+’
         pairs = (pairs+count);
                  ~~~~~^~~~~~

3 个答案:

答案 0 :(得分:1)

count = (count/2)pairs = (pairs+count)中,您没有引用您声明的int,因为它不在范围内。您实际上是在指功能std::count,因为您在该编译单元中的某处有using namespace std;。这就是您shouldn't do that的原因之一。

要解决此问题,您需要在适当的范围内声明count

int sockMerchant(int n, vector<int> ar) {
    int pairs;
    int count = 0;

    for (int i = 1; i <= 100 ; i++) { //for every number ("Color") between 1 and 100
        for (int j = 0; j < n; j++) { //iterate thru array to look for it
            if (ar[j] == i) { //once found,
                for (int k = j; k < n ; k++) { //count how many of that number is there
                    if (ar[k] == i) {
                        count++;
                    }
                }
            count = (count/2);
            pairs = (pairs+count);
            }
        }
    }
    return pairs;
}

答案 1 :(得分:0)

将计数放在for循环之外,应该可以解决。

答案 2 :(得分:0)

首先,count是在没有值的范围内定义的。然后,您可以在表达式中使用它:count++;

不仅这种不确定的行为,而且count在范围if(ar[k] == i)之后甚至没有

然后您决定在另一个表达式中使用count和不在当前作用域中的变量:count = (count/2);

提示:请勿在除法中使用整数。该值将被截断。

最后,您使用pairs,该表达式尚未使用先前未声明的countpairs = (pairs + count); 中使用自身初始化>

TL; DR: countpairs均未正确使用。确保将它们都初始化为某个值(在这种情况下为0),并将它们设置在适当的范围内。