C++ 确定一个数字是十的倍数还是在一组特定的范围内

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23330100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:25:24  来源:igfitidea点击:

Determining if a number is either a multiple of ten or within a particular set of ranges

c++comparisonconditional-statementsinteger-arithmetic

提问by user3419168

I have a few loops that I need in my program. I can write out the pseudo code but I'm not entirely sure how to write them logically.

我的程序中需要一些循环。我可以写出伪代码,但我不完全确定如何合乎逻辑地编写它们。

I need -

我需要 -

if (num is a multiple of 10) { do this }

if (num is within 11-20, 31-40, 51-60, 71-80, 91-100) { do this }
else { do this } //this part is for 1-10, 21-30, 41-50, 61-70, 81-90

This is for a snakes and ladders board game, if it makes any more sense for my question.

这是一个蛇和梯子棋盘游戏,如果它对我的问题更有意义的话。

I imagine the first if statement I'll need to use modulus, would if (num == 100%10)be correct?

我想我需要使用模数的第一个 if 语句if (num == 100%10)是正确的吗?

The second one I have no idea. I can write it out like if (num > 10 && num is < 21 || etc)but there has to be something smarter than that.

第二个我不知道。我可以写出来,if (num > 10 && num is < 21 || etc)但必须有比这更聪明的东西。

采纳答案by Winston Ewert

For the first one, to check if a number is a multiple of use:

对于第一个,检查一个数字是否是使用的倍数:

if (num % 10 == 0) // It's divisible by 10

For the second one:

对于第二个:

if(((num - 1) / 10) % 2 == 1 && num <= 100)

But that's rather dense, and you might be better off just listing the options explicitly.

但这相当密集,您最好明确列出选项。



既然您已经对自己在做什么有了更好的了解,我会将第二个写为:

   int getRow(int num) {
      return (num - 1) / 10;
   }

   if (getRow(num) % 2 == 0) {
   }

It's the same logic, but by using the function we get a clearer idea of what it means.

这是相同的逻辑,但是通过使用该函数,我们可以更清楚地了解它的含义。

回答by Adam Liss

if (num is a multiple of 10) { do this }

if (num 是 10 的倍数) { 这样做 }

if (num % 10 == 0) {
  // Do something
}

if (num is within 11-20, 31-40, 51-60, 71-80, 91-100) { do this }

if (num 在 11-20, 31-40, 51-60, 71-80, 91-100) { 这样做 }

The trick here is to look for some sort of commonality among the ranges. Of course, you can always use the "brute force" method:

这里的技巧是寻找范围之间的某种共性。当然,您始终可以使用“蛮力”方法:

if ((num > 10 && num <= 20) ||
    (num > 30 && num <= 40) ||
    (num > 50 && num <= 60) ||
    (num > 70 && num <= 80) ||
    (num > 90 && num <= 100)) {
  // Do something
}

But you might notice that, if you subtract 1from num, you'll have the ranges:

但是,你可能会注意到,如果你减去1num,你就会有范围:

10-19, 30-39, 50-59, 70-79, 90-99

In other words, all two-digit numbers whose first digit is odd. Next, you need to come up with a formula that expresses this. You can get the first digit by dividing by 10, and you can test that it's odd by checking for a remainder of 1 when you divide by 2. Putting that all together:

换句话说,所有第一位为奇数的两位数。接下来,您需要想出一个公式来表达这一点。您可以通过除以 10 来获得第一个数字,并且您可以通过检查除以 2 时是否有 1 的余数来测试它是否为奇数。将所有这些放在一起:

if ((num > 0) && (num <= 100) && (((num - 1) / 10) % 2 == 1)) {
  // Do something
}

Given the trade-off between longer but maintainable code and shorter "clever" code, I'd pick longer and clearer every time. At the very least, if you try to be clever, please, please include a comment that explains exactly what you're trying to accomplish.

考虑到更长但可维护的代码和更短的“聪明”代码之间的权衡,我每次都会选择更长更清晰的代码。至少,如果您想变得更聪明,请添加一条评论,准确解释您要实现的目标。

It helps to assume the next developer to work on the code is armed and knows where you live. :-)

假设下一个处理代码的开发人员是武装的并且知道你住在哪里是有帮助的。:-)

回答by Bryan Chen

If you are using GCC or any compiler that supports case rangesyou can do this, but your code will not be portable.

如果您使用 GCC 或任何支持大小写范围的编译器,您可以这样做,但您的代码将不可移植

switch(num)
{
case 11 ... 20:
case 31 ... 40:
case 51 ... 60:
case 71 ... 80:
case 91 ... 100:
    // Do something
    break;
default:
    // Do something else
    break;
}

回答by chris

This is for future visitors more so than a beginner. For a more general, algorithm-like solution, you can take a list of starting and ending values and check if a passed value is within one of them:

这对于未来的访问者来说比初学者更重要。对于更通用的类似算法的解决方案,您可以获取起始值和结束值的列表,并检查传递的值是否在其中之一内:

template<typename It, typename Elem>
bool in_any_interval(It first, It last, const Elem &val) {
    return std::any_of(first, last, [&val](const auto &p) {
        return p.first <= val && val <= p.second;
    });
}

For simplicity, I used a polymorphic lambda (C++14) instead of an explicit pairargument. This should also probably stick to using <and ==to be consistent with the standard algorithms, but it works like this as long as Elemhas <=defined for it. Anyway, it can be used like this:

为简单起见,我使用了多态 lambda (C++14) 而不是显式pair参数。这应该也可能会坚持使用<,并==能与标准算法一致,但它是这样工作的,只要Elem<=为它定义。无论如何,它可以像这样使用:

std::pair<int, int> intervals[]{
    {11, 20}, {31, 40}, {51, 60}, {71, 80}, {91, 100}
};

const int num = 15;
std::cout << in_any_interval(std::begin(intervals), std::end(intervals), num);

There's a live example here.

有一个活生生的例子在这里

回答by kasimir

The first one is easy. You just need to apply the modulo operator to your num value:

第一个很容易。您只需要将模运算符应用于您的 num 值:

if ( ( num % 10 ) == 0)

Since C++ is evaluating every number that is not 0 as true, you could also write:

由于 C++ 将每个不为 0 的数字计算为真,您还可以编写:

if ( ! ( num % 10 ) )  // Does not have a residue when divided by 10

For the second one, I think this is cleaner to understand:

对于第二个,我认为这样更容易理解:

The pattern repeats every 20, so you can calculate modulo 20. All elements you want will be in a row except the ones that are dividable by 20.

该模式每 20 次重复一次,因此您可以计算模 20。除可被 20 整除的元素外,您想要的所有元素都将排成一行。

To get those too, just use num-1 or better num+19 to avoid dealing with negative numbers.

要获得这些,只需使用 num-1 或更好的 num+19 以避免处理负数。

if ( ( ( num + 19 ) % 20 ) > 9 )

This is assuming the pattern repeats forever, so for 111-120 it would apply again, and so on. Otherwise you need to limit the numbers to 100:

这是假设模式永远重复,因此对于 111-120 它将再次应用,依此类推。否则,您需要将数字限制为 100:

if ( ( ( ( num + 19 ) % 20 ) > 9 ) && ( num <= 100 ) )

回答by La-comadreja

With a couple of good comments in the code, it can be written quite concisely and readably.

代码中有几个很好的注释,它可以写得非常简洁和可读。

// Check if it's a multiple of 10
if (num % 10 == 0) { ... }

// Check for whether tens digit is zero or even (1-10, 21-30, ...)
if ((num / 10) % 2 == 0) { ... }
else { ... }

回答by Henry Harris

You basically explained the answer yourself, but here's the code just in case.

您基本上自己解释了答案,但这里是代码以防万一。

if((x % 10) == 0) {
  // Do this
}
if((x > 10 && x < 21) || (x > 30 && x < 41) || (x > 50 && x < 61) || (x > 70 && x < 81) || (x > 90 && x < 101)) {
  // Do this
}

回答by usr2564301

You might be overthinking this.

你可能想多了。

if (x % 10)
{
   .. code for 1..9 ..
} else
{
   .. code for 0, 10, 20 etc.
}

The first line if (x % 10)works because (a) a value that is a multiple of 10 calculates as '0', other numbers result in their remainer, (b) a value of 0 in an ifis considered false, any other value is true.

第一行if (x % 10)之所以有效,是因为 (a) 10 的倍数的值计算为“0”,其他数字的结果为它们的余数,(b) an 中的值 0if被考虑false,任何其他值都是true

Edit:

编辑:

To toggle back-and-forth in twenties, use the same trick. This time, the pivotal number is 10:

要在二十多岁来回切换,请使用相同的技巧。这一次,关键数字是10

if (((x-1)/10) & 1)
{
  .. code for 10, 30, ..
} else
{
   .. code for 20, 40, etc.
}

x/10returns any number from 0 to 9 as 0, 10 to 19 as 1and so on. Testing on even or odd -- the & 1-- tells you if it's even or odd. Since your ranges are actually "11 to 20", subtract 1 before testing.

x/10返回 0 到 9 as 0、10 到 19 as 之间的任何数字1,依此类推。测试偶数或奇数 -- & 1-- 告诉你它是偶数还是奇数。由于您的范围实际上是“11 到 20”,因此在测试前减去 1。

回答by Khaled.K

For the first one:

对于第一个:

if (x % 10 == 0)

will apply to:

将适用于:

10, 20, 30, .. 100 .. 1000 ...

For the second one:

对于第二个:

if (((x-1) / 10) % 2 == 1)

will apply for:

将申请:

11-20, 31-40, 51-60, ..

We basically first do x-1to get:

我们基本上先做x-1得到:

10-19, 30-39, 50-59, ..

Then we divide them by 10to get:

然后我们将它们除以10得到:

1, 3, 5, ..

So we check if this result is odd.

所以我们检查这个结果是否是奇数。

回答by ShalakaV

You can try the following:

您可以尝试以下操作:

        // multiple of 10
        if ((num % 10) == 0)
        {
           // Do something
        }
        else if (((num / 10) % 2) != 0)
        {
            //11-20, 31-40, 51-60, 71-80, 91-100
        }
         else
        {
            //other case
        }