[英]Can someone please explain how the output was obtained for this function?
int main(int i, int j) {
for (i=4; i>0; i--) {
j=i;
while (j>=0) {
printf("X");
j--;
}
printf("%lf\n", (1.0*(i)) / (j+2));
}
}
Output: 输出:
XXXXX 4.0
XXXX 3.0
XXX 2.0
XX 1.0
The >=
sign is probably confusing you. >=
符号可能让您感到困惑。 The code prints out X
5 times in the first row instead of 4 (if that's what you mean) is because once j = 0
, the loop continues once more. 代码在第一行中输出
X
5次而不是4次(如果这是你的意思)是因为一旦j = 0
,循环再次继续。
Basically, the value of j
after the while
loop ends is -1
. 基本上,
while
循环结束后j
的值为-1
。 Substitute it into your last printf
and the rest of the output makes sense. 将它替换为最后一个
printf
,剩下的输出是有意义的。
If you change the >=
to a >
, the code will produce the correct output. 如果将
>=
更改为>
,则代码将生成正确的输出。
why does the first line print 5 "X's"? 为什么第一行打印5“X”? & why is the first number 4.0?
为什么第一个数字是4.0?
Because, 因为,
j takes values of j = 4,3,2,1,0. j取值j = 4,3,2,1,0。 Each time it is printing X hence 5X.
每次打印X因此为5X。
After that loop j becomes -1. 在那个循环之后j变为-1。
Now 1.0*(4) /(-1+2)
=> (4.0/1)
=> 4.0
现在
1.0*(4) /(-1+2)
=> (4.0/1)
=> 4.0
Hence the output is XXXXX 4.0
因此输出为
XXXXX 4.0
Well, j is set to i
, so it prints X
j+1
times due to the >= 0
check. 好吧,j设置为
i
,所以由于>= 0
检查,它打印X
j+1
次。 Then divides i
by j
, now -1 + 2. which is now one, to get i
, which it prints to the screen before a newline begins. 然后将
i
除以j
,现在为-1 + 2.现在是1,得到i
,它在换行开始之前打印到屏幕上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.