For循环没有第二个条件,即布尔检查? [英] For loop without the second condition, i.e. the boolean check?

查看:243
本文介绍了For循环没有第二个条件,即布尔检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须写一个计算底数的地板传入一个unsigned int 16函数。有限制的,以什么运营商,什么常数,我们被允许使用,我们只能专门使用循环。

I have to write a function that calculates the floor of log base 16 of an unsigned int passed in. There are restrictions as to what operators and what constants we are allowed to use, and we can only use specifically for loops.

为了清晰起见,我们不能使用任何条件语句(如果,否则,切换...)。该函数原型为:

For clarity, we cannot use any conditional statements(if, else, switch ... ). The function prototype is:

int floor_log16(unsigned int x); 

允许运营商: ++ - = &安培; | ^ << >!>

允许的常量: 1 2 3 4 8 16

Allowed constants: 1 2 3 4 8 16

我写了一个版本的程序如下:

I wrote a version of the program as follows:

int floor_log16(unsigned int x) {
    int index=1;
    int count=(1!=1);

    count--;

    for(; index<=x; index<<=4) {
        count++;
    }

    return count;
}

这似乎为所需的工作。但是,我意识到,根据后来的功能和所需的功能,我们必须编写描述,我注意到,在允许运营商有时&GT; &LT; 上市。

我推断这意味着因为对于 floor_log16 功能上面列出,我们并没有明确告知使用&GT; &LT; ,我只能假设,上面贴的解决方案将不被接受。

I deduce this implies that since for the floor_log16 function listed above, we weren't explicitly told to use > or <, I can only assume that the solution posted above will not be accepted.

这让我相当困惑,因为我不明白你怎么能有一个for循环没有布尔检查?

This leaves me rather confused because I don't understand how you can possibly have a for loop without a boolean check?

是不是循环迭代的整体思路,而一个条件得到满足?

Isn't the whole idea of a loop to iterate while a condition is met?

推荐答案

嗯,首先, -loop没有布尔检查是完全正常的。例如,

Well, first of all, for-loop without the boolean check is perfectly fine. For example,

for (;;)

写作是一种常见的方式。

is a common way of writing

while (true)

二,有一个 -loop与其他部件,但没有布尔检查仍然是有用的,你可以用返回退出它

Second, having a for-loop with other parts but without boolean check is still useful as you can exit it with return or break.

和的最后一件事。有吨得到一个布尔值的方法,而无需使用&LT; &GT; 。例如,您可以简单地使用 I 检查我!= 0 等。

And the last thing. There are tons of ways of getting a boolean without using < and >. For example, you can simply use i to check that i != 0 and so on.

例如,如果你想检查 A&LT; b 您可以检查(A - B)&LT; 0 来代替。执行加法(因此减法)与位运算符是一个众所周知的面试问题(你确实应该尝试自己做,很有趣),并检查你的 INT 为负是看其最显著位一样容易。

For example if you want to check that a < b you can check for (a - b) < 0 instead. Implementing addition (and hence subtraction) with bitwise operators is a well known interview question (you should really try to do this yourself, it's fun), and checking that your int is negative is as easy as looking at its most significant bit.

这篇关于For循环没有第二个条件,即布尔检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆