gpt4 book ai didi

c++ - 加法和整数除法的无效操作数错误?

转载 作者:行者123 更新时间:2023-11-30 04:56:30 25 4
gpt4 key购买 nike

这是我的功能。我想知道为什么我不能对两个 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);
~~~~~^~~~~~

最佳答案

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;
}

关于c++ - 加法和整数除法的无效操作数错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52462662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com