gpt4 book ai didi

algorithm - 在没有循环或 if 语句的情况下执行循环 x 次

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:03:38 25 4
gpt4 key购买 nike

我如何重写以下程序才能不使用任何循环和分支结构? (没有 if、while、break、continue、switch、...)

for(int i=0; i < 5; i++){
// do stuff
}

我能想到的唯一方法是使用丑陋的 goto 语句:

loop:
// do stuff
goto loop;

但是我怎样才能在刚好运行 5 次后退出这个循环呢?或者有什么不同的方法吗?

编辑:解决方案不应该是递归的。类(class)中尚不允许调用函数。

最佳答案

您可以使用递归函数并将参数作为计数器传递。
每次调用前减少计数器。

int func(int a,int counter)
{
int c;


// .. your logic
return counter==0?a:func(a,counter-1);

}

这行 return counter==0?a:func(a,counter-1); 帮助您处理 counter==0 时的情况,而无需使用 if。

关于algorithm - 在没有循环或 if 语句的情况下执行循环 x 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29816712/

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