问题描述
限时送ChatGPT账号..我目前正在完成C 编程语言"中的练习.这是我的解决方案之一:
I'm currently working through the excercises in 'The C Programming Language'. Here's one of my solutions:
int c;
while ((c=getchar()) != EOF) {
if (c == ' ') {
while ((c = getchar()) == ' ')
{} // do nothing?
putchar(' ');
}
putchar(c);
}
我在这里找到了一些与我和我的完全不同的解决方案使用一个额外的变量来跟踪正在发生的事情,而我只是使用一个 while 循环来跳过所有空间.我的解决方案感觉有点混乱,因为在花括号之间没有任何东西的 while 循环似乎有点hackish.我想知道是否有任何充分的理由不这样做?感谢您的任何建议:-)
I found some solutions here that are quite different to mine and use an extra variable to keep track of what's going on, whereas I just use a while loop to skip through all the spaces. My solution feels a bit messy, as it seems bit hackish to have a while loop with nothing between the curly braces. I was wondering if there are any good reasons not to do this? Thanks for any advice :-)
推荐答案
完全没有 - 我相信你会在 K&R 中找到类似这样的无用循环,所以这与它得到的一样正式.
Not at all - I believe you'll find do-nothing loops like these in K&R, so that's about as official as it gets.
这是个人喜好的问题,但我更喜欢这样的无操作循环:
It's a matter of personal preference, but I prefer my do-nothing loops like this:
while(something());
其他人更喜欢将分号放在单独的行上,以强调它是一个循环的事实:
Others prefer the semicolon to go on a separate line, to reinforce the fact that it's a loop:
while(something())
;
还有其他人更喜欢使用没有任何内容的括号,就像您所做的那样:
Still others prefer to use the brackets with nothing inside, as you have done:
while(something())
{
}
这一切都是有效的——你只需要选择你喜欢的风格并坚持下去.
It's all valid - you'll just have to pick the style you like and stick with it.
这篇关于使用 while 块什么都不做是件坏事吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论