使用三元运算符时出现 "expression must have integral type" 错误

Getting "expression must have integral type" error when using Ternary Operator

float sigma;
// ...
int kernel_size = ((6.0 * sigma) % 2 == 0) ? (6 * sigma + 1) : (6 * sigma);

在这一行中,我想使用三元运算符获得大于 6*sigma 值的最小整数。顺便说一句 sigma 是浮动的。

  1. 我不确定上面的代码是否正确。
  2. 我也无法编译,得到 expression must have integral type

您的代码肯定是错误的,因为它无法编译。

使用ceil(x)(returns不小于x的最小整数),你的计算可以这样进行:

float sigma;
// ...
float s6 = 6.0 * sigma;
float c = ceil(s6);
int kernel_size = c == s6 ? c + 1 : c;