这是什么片code的做,什么也各自使用的符号是什么意思?使用的语言是C,我只是个初学者编码 [英] What does this piece of code do and what does each of the symbols used mean? The language used is C and I am just a beginner to coding
问题描述
跨code,而我不明白这两条线是做来了。拿不拿的语法。请具体说明是什么类型的功能已被使用像如我猜测,出现了第一行使用条件运算符。
无符号长长base_size = B> = 2? (B-2)/ 2:0;
的printf(%LLU \\ n,(base_size *(base_size + 1))/ 2);
由于每的运算符优先级是C,第一行是有效的。
无符号长长base_size =(B> = 2(B-2)/ 2:0);
现在,在除权pression()
使用的三元操作或有条件的运营商。
由于每 C11
标准,章节6.5.15,语法是
有条件-EX pression:
逻辑或-EX pression
逻辑或-EX pression?前pression:有条件-EX pression
和语义是[关注我的重点]
第一个操作数计算; 之间是有顺序的点
评价和在第二或第三操作数的评价
(取计算)。 第二个操作数只有当评估
首先比较不等于0;第三个操作数只计算,如果
第一比较等于0;其结果是,第二值
或第三个操作数(取计算)转换为下面描述的类型注意。
注意:有条件的前pression不会产生左值
块引用>所以,紧接着,你的情况,
B> = 2? (B-2)/ 2:0
第一,第一八佰伴pression,
B> = 2
进行评估。如果B
的值大于或等于2
,它返回1
,否则0
。
如果计算结果为
1
,第二个操作数,(B-2)/ 2
是执行,条件运算符的最终结果是前pression的价值。同样,它的计算结果为
0
,第三个操作数0
作为返回的结果有条件的经营者。最后,三元运算符的返回值被用来初始化
无符号长长base_size
变量。关于第二行,
的printf()
是一个标准C库函数,在stdio.h中
原型。你可以找到更多关于这个这里。Came across a code of which I couldn't understand what these two lines are doing. Can't even get the syntax. Please specify what type of functionalities have been used like for eg I am guessing that there has been a use of conditional operators in the first line.
unsigned long long base_size = b >= 2 ? (b-2)/2:0; printf("%llu\n",(base_size*(base_size+1))/2);
解决方案As per the operator priority is c, the first line is effectively
unsigned long long base_size = ( b >= 2 ? (b-2)/2:0 );
Now, the expression inside
( )
uses a ternary operator or Conditional operator.As per the
C11
standard, chapter 6.5.15, the syntax isconditional-expression: logical-OR-expression logical-OR-expression ? expression : conditional-expression
and the semantics is [follow my emphasis]
The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (whichever is evaluated) converted to the type described belowNOTE.
NOTE: A conditional expression does not yield an lvalue.
So, following that, your case,
b >= 2 ? (b-2)/2:0
first, the first expression,
b >= 2
is evaluated. ifb
has value greater than or equal to2
, it returns1
, otherwise,0
.
if it evaluates to
1
, the second operand,(b-2)/2
is executed and the final result of the conditional operator is the value of the expression.similarly, it evaluates to
0
, the third operand0
is returned as the result of the conditional operator.Finally, the return value of the ternary operator is used to initialize the
unsigned long long base_size
variable.About the second line,
printf()
is a standard C library function, prototyped instdio.h
. You can find more on this here.这篇关于这是什么片code的做,什么也各自使用的符号是什么意思?使用的语言是C,我只是个初学者编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!