[英]The output of a certain part of my for loop
#include <stdio.h>
int num, i, k, a[5];
int main() {
a[0]=2;
a[1]=11;
a[2]=12;
a[3]=16;
a[4]=28;
num=a[1+3]
i=4;
while(num>0){
a[i]=num%4;
num=num/3;
printf("%d ",num);
i--;
}
printf("8\n");
for(k=0;k<5;k++){
printf("%c ",65+a[k]);
}
printf("\n);
}
The output of this program is:这个程序的输出是:
9 3 1 0 8 9 3 1 0 8
CBDBA生物多样性公约
I understand completely how the output for the first line is but am rather confused about the 2nd part.我完全理解第一行的输出如何,但对第二部分感到相当困惑。
for(k=0;k<5;k++){
printf("%c ",65+a[k]);
This bit here confused me as the loop the first time from my understanding should go k=0 then print %c which comes from 65+a[k] which k is currently 0 so 65+a[0].这一点让我感到困惑,因为根据我的理解,循环第一次应该是 k=0 然后打印 %c 来自 65+a[k] 其中 k 当前为 0 所以 65+a[0]。 From the earlier part of the where its setting we see a[0]=2 and 65+2 is 67 which is the character "C".从前面的部分,我们看到 a[0]=2 和 65+2 是 67,它是字符“C”。 which is correct on the output but if I follow this same logic for the 2nd loop 65+a[k] where k=1 so 65+a[1] and a[1] is 11 and 65+11 is 76 that would equal the character "K" but that's wrong as it should be the character "B".这在输出上是正确的,但如果我对第二个循环 65+a[k] 遵循相同的逻辑,其中 k=1 所以 65+a[1] 和 a[1] 是 11,65+11 是 76,这将等于字符“K”但这是错误的,因为它应该是字符“B”。
I feel that this line of code is where im missing something:我觉得这行代码是我遗漏的地方:
a[i]=num%4
but it doesn't actually set a number so still confused.但它实际上并没有设置一个数字,所以仍然很困惑。
Any help is appreciated任何帮助表示赞赏
a[i]=num%4
does set the number. a[i]=num%4
确实设置了数字。 This is how:这是如何:
In your loop:在你的循环中:
while(num>0){
a[i]=num%4;
num=num/3;
printf("%d ",num);
i--;
}
num
varies as in the first line of output. num
与输出的第一行相同。
a[i]=num%4;
actually sets the values in the array as follows:实际上设置数组中的值如下:
Initially, i=4
and num=28
.最初, i=4
和num=28
。 Therefore,所以,
a[i]=num%4;
sets a[4]
as 28%4=0
.将a[4]
为28%4=0
。 Therefore, your last character is A+0=A
.因此,您的最后一个字符是A+0=A
。
Then i=3
, and num=9
.然后i=3
和num=9
。 Therefore,所以,
a[i]=num%4;
sets a[3]
as 9%4=1
.将a[3]
为9%4=1
。 Therefore, your second last character is A+1=B
.因此,您的倒数第二个字符是A+1=B
。
Then i=2
, and num=3
.然后i=2
和num=3
。 Therefore,所以,
a[i]=num%4;
sets a[2]
as 3%4=3
.将a[2]
为3%4=3
。 Therefore, your third last character is A+3=D
.因此,您的倒数第三个字符是A+3=D
。
Then i=1
, and num=1
.然后i=1
和num=1
。 Therefore,所以,
a[i]=num%4;
sets a[1]
as 1%4=1
.将a[1]
为1%4=1
。 Therefore, your fourth last character is A+1=B
.因此,您的倒数第四个字符是A+1=B
。
Then i=0
, and num=0
.然后i=0
和num=0
。 Therefore,所以,
We do not enter the loop.我们不进入循环。 a[0]=C
, its initial value. a[0]=C
,它的初始值。
Hence we get: CBDBA
因此我们得到: CBDBA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.