1

Suppose I have a variable x (double) that lies between 0 and 100. If x is in any of the intervals (0+10*n,5+10*n), with n (int) =0,...,9, then I return n, otherwise I break. I was thinking of doing this

bool test = false;
int k;

for(int i=0; i<10; i++){

    if((0+10*i)<x<(5+10*i)){
        k = i;
        test = true;
    }
}

if(test) return k;
else break;

would this be correct? If so, is there any other way that avoids loops?

4

2 回答 2

3

这取决于您想到的间隔。由于您的区间有一个模式,您可以使用数学公式而不是循环:

if(((int)x % 10) < 5) return (int)(x / 10);
else break;

%这里是模运算符。)

由于 C++ 的%运算符不适用于双精度数,因此您可以x转换为整数(如图所示),或使用该fmod函数(适用于非整数区间)。

于 2019-10-28T07:17:00.667 回答
0

您可以使用 % 运算符来获取它的 mod。得到 x % 10 并检查 mod 的结果是否在 0 和 5 之间。它可以比这更快。

于 2019-10-28T07:16:46.457 回答