需要如果构建建议
我有一个 for 循环,其中放置了几个 if 语句。这些条件的目的是检查数字的整除性,如果该数字可以被 3 整除,则输出一个字符串。如果该数字可以被 5 整除,则将输出另一个字符串。但是,如果该数字可以同时被 3 和 5 整除,则将在其位置输出完全不同的字符串,而不是其他字符串。
这是我的代码:
for (i = 1; i <= file_int; i++){
if (i % 3 == 0) {
printf("Hoppity \n");
}
if (i % 5 == 0) {
printf("Hophop \n");
}
if (i % 5 == 0 && i % 3 == 0) {
printf("Hop \n");
}
}
如您所见,最后一个条件不太有效。我应该使用什么类型的控制结构?别的?
多谢。
I have a for loop in which I placed several if statements. The objective of these conditionals is to check divisibility of a number and then output a string if the number is divisible by 3. If the number is divisible by 5, another string will be outputted. However, if the number is divisible by both 3 and 5, an entirely different string will be outputted in its place instead of the other strings.
Here is my code:
for (i = 1; i <= file_int; i++){
if (i % 3 == 0) {
printf("Hoppity \n");
}
if (i % 5 == 0) {
printf("Hophop \n");
}
if (i % 5 == 0 && i % 3 == 0) {
printf("Hop \n");
}
}
As you can see, the last conditional doesn't quite work. What type of control construct should I use? else?
Thanks alot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会使用
else-ifs
并让我们知道(i % 5 == 0 && i % 3 == 0) <=> (i % 15 == 0)
:当然,除了
for
循环之外,您也可以不使用任何控制结构就可以逃脱:对于这个例子来说,这个解决方案有点疯狂,但是它展示了如何以不同的方式做事(并且在编写代码时,在一个函数中永远不会有超过一定数量的分支路径(过度热心的编码约定......))。
I would use
else-ifs
and make us of the fact that(i % 5 == 0 && i % 3 == 0) <=> (i % 15 == 0)
:Of course you can also get away without using any control structures except the
for
-loop at all:That solution is slightly insane for this example, but it shows how you can do things differently (and it's not so farfetched when writing code where you shall never ever have more then a certain number of branch paths in one function (overzealous coding conventions...)).
只是为了它,而不推荐它,因为它可能更难阅读,因为它滥用从
bool
到int
的转换:可以进一步压缩为
:当然,这两种解决方案都违背了问题本身,因为它们不是 if 构造,而是避免在第一种情况下使用 if 和 分支 一般在第二种情况下。
Just for the sake of it, and not recommending it, as it can be harder to read as it abuses conversions from
bool
toint
:which can be further condensed into:
Of course, both solutions are against the question itself, as they are not if constructs, but rather avoid the use of if in the first case, and branches in general in the second case.
另一种解决方案,更接近您的原始代码。尽管
else
解决方案确实更高效(也更优雅)。An alternative solution, keeping closer to your original code. Although the
else
solution is indeed more efficient (and elegant).