gpt4 book ai didi

c++优先顺序 - 在乘法之前进行类型转换

转载 作者:行者123 更新时间:2023-11-28 01:36:27 25 4
gpt4 key购买 nike

在下面的 C++ 函数中,为什么要将 numbers[max_index1] 转换为 long long 然后乘以 numbers[max_index2]?我会认为你会乘以数字然后转换?

此外,将 vector 数字类型设置为 long long 而不是 int 是否更有意义,因此不需要强制转换?

long long MaxPairwiseProductFast(const vector<int>& numbers) {

int n = numbers.size();

int max_index1 = -1;
cout << "value at max_index1 is " << numbers[max_index1] << std::endl;
for(int i = 0; i < n; i++)
if((max_index1 == -1) || (numbers[i] > numbers[max_index1]))
max_index1 = i;


int max_index2 = -1;
for(int j = 0; j < n; j++)
if((numbers[j] != numbers[max_index1]) && ((max_index2 == -1) || (numbers[j] > numbers[max_index2])))
max_index2 = j;

return ((long long)(numbers[max_index1])) * numbers[max_index2];
}

int main() {
int n;
cin >> n;
vector<int> numbers(n);
for (int i = 0; i < n; ++i) {
cin >> numbers[i];
}

long long result = MaxPairwiseProductFast(numbers);
cout << result << "\n";
return 0;
}

最佳答案

((long long)(numbers[max_index1])) * numbers[max_index2];
在执行乘法之前,

numbers[max_index2] 将被提升为 long long。如果将两个 int 相乘 并且结果溢出,则将该结果转换为 long long 无法实现任何结果,因此您首先 cast,然后相乘。

Also would be not make more sense to make the vector numbers type long long instead of int therefore the casting wouldn't be necessary?

如果您知道单个数字适合 int,但两个 int 相乘的结果可能会溢出,这将有助于节省空间。

关于c++优先顺序 - 在乘法之前进行类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49067649/

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