我如何写这个for for while或while while循环? [英] How do I write this for loop as a while or do while loop?

查看:84
本文介绍了我如何写这个for for while或while while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

for(k = 0; k <2500; k ++)

x [k] = 2500-k;

for(k = 0; k < 2500; k++)
x[k] = 2500-k;

推荐答案

这是完全取决于你。我个人会把它留作for循环。 Bruno(0x01AA)在对该问题的评论中请参阅变体 - 代码更长,没有任何其他性能的明显好处。他还说明了我将在下面提出的观点。



我会改变另一件事,我认为这是不可接受的。看一下:你使用立即常量 2500.你可以写一个显式的常量声明。但是你明白这里最糟糕的是什么吗?你有两次2500写,你很可能在其他地方需要这个值。想象一下,你必须改变这个值,你会做什么?在N个地方改变它?!上帝保佑......



没有任何理由可以保持不变。它只会降低算法的抽象级别。当然,它应该是一个变量,可能是某个函数的参数。它最初应该在哪里?好吧,它可能是输入数据的一部分,任何东西。即使是常量,但该常量应该是显式定义的常量,可能与其他常量组合,依此类推。为什么?为了可维护性和重用。



-SA
It's up to you, entirely. I personally would leave it as a "for" loop. Please see the while variant by Bruno (0x01AA) in his comment to the question — the code is longer, without apparent benefits of performance of anything else. He also illustrated the point I'll make below.

I would change another thing, which I consider simply unacceptable. Take a look: you use immediate constant 2500. You could write an explicit constant declaration. But do you understand what's the worst thing here? You have 2500 written twice, and it's very likely that you need this value elsewhere. Imagine you have to change this value, what will you do? Change it in N places?! God forbid…

There is not any reason to have such constant. It only reduce level of abstraction of your algorithm. Of course, it should be a variable, possibly a parameter of some function. And where it should be taken originally? Well, it could be a part of input data, anything. Even a constant, but that constant should be an explicitly defined constant, probably grouped with other constants, and so on. Why? For maintainability and reuse.

—SA


简单,打开你的C ++课本和外观循环。这里没有人会为你做功课。
Simple, open your C++ class book and look up Loops. No one here is going to do your homework for you.


这篇关于我如何写这个for for while或while while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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