有谁有C语言条件语句的例子吗?
像这样的东西,我想看看完整的语法。
伪代码:
var = user_input
if var > 5:
output = 'var > 5'
else:
output = 'var < 5'
Something like this, I'd like to see the full syntax.
Pseudo Code:
var = user_input
if var > 5:
output = 'var > 5'
else:
output = 'var < 5'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
怎么样:
进行几次测试运行:
How about something along the lines of:
with a couple of test runs:
希望这能帮助您入门。
Hope this will help you get started .
这似乎符合您的需求:
关于使用
scanf()
的注意事项 - 我通常不喜欢它的弹性代码,但它很快给出了最小的答案。您必须将其包装在
main()
和#include
中才能使其可执行:This seems to correspond to what you'd like:
With caveats about using
scanf()
- I generally don't like it for resilient code, but it gives a minimal answer swiftly.You'd have to wrap it in a
main()
and#include <stdio.h>
to make it executable:除了其他两个答案之外,总是有三元运算符
?:
,可以这样使用:In addition to the other two answers, there's always the ternary operator
?:
which can be used like this:这几乎就是你所拥有的。您的示例:
唯一的区别是语句后面需要分号,条件表达式周围需要括号,而冒号不是必需的。
您还可以使用花括号来表示在给定特定条件下执行的命令块。然而,当只执行一行时,则不需要大括号。但这相当于:
您可以在
if
之后或在else
之后使用大括号,或者两者都使用,或者两者都不使用。但请记住,对于多个语句,需要使用大括号。还值得注意的是,换行符是可选的。这可以写成
甚至
但是这段代码的可读性要差得多。第一种和第二种形式是更好的练习。
It's pretty much what you've got there. Your example:
The only difference is that you need semicolons after the statements and parentheses around the conditional expression, and the colons are not required.
You can also use curly braces to denote a block of commands to execute given a certain condition. When there's only one line being executed, however, the braces are not necessary. But this is equivalent to:
You can have braces just after the
if
or just after theelse
, or both, or neither. Remember, though, that with multiple statements the braces are required.It's also worth noting that the line breaks are optional. This could be written
Or even
But this code is far less readable. The first and second forms are better practice.