大门|大门-CS-2017(第1组)|问题64

执行以下C程序的输出为。

null
# include 

int total(int v) 
{ 
   static int count = 0; 
   while (v) { 
     count += v & 1; 
     v >>= 1; 
   } 
   return count; 
} 

void main() 
{ 
   static int x = 0; 
   int i = 5; 
   for (; i> 0; i--) { 
       x = x + total(i); 
   } 
   printf (“%d”, x) ; 
} 

(A) 23 (B) 24 (C) 26 (D) 27 答复: (A) 说明: 数字:5-0101,4-0100,3-0011,2-0010,1-0001 1的计数:2,3,5,6,7

总计:2+3+5+6+7=23

总计(i)=23

因此 选项A 这是正确的

查看正在运行的代码并附上注释:

#include<stdio.h>
int total( int v)
{
static int count = 0;
while (v)
{
count += v&1;
v >>= 1;
}
//This count can be used to see number of 1s returned
//for every number i
//printf("%d", count);
return count;
}
void main()
{
static int x=0;
int i=5;
for (; i>0; i--)
{
//total gets added everytime with total number
//of digits in the given number i
x = x + total(i);
}
printf ( "%d" , x);
}


替代解决方案: g-set1_a64

这个解决方案是由 帕鲁尔·夏尔马 这个问题的小测验

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享