此题可以用一个for循环,计数变量初值赋1,将其每次左移一位累加,运算到计数变量等于64即可获得结果。代码如下:
#include "stdio.h"
int main(int argc,char *argv[]){
int s,i;
for(s=0,i=1;i<=64;s+=(i<<=1));//由于先左移后累加,所以实质是s=2+4+6+...+128
printf("2+4+8+16+...+128 = %d\n",s);
return 0;
}
运行举例如下图:
#include
int main()
{
int i = 2,s =0 ;
for(i=2; i <= 128; i = i*2)
s += i;
printf("s = %d\n" , s);
return 0;
}
#include(stdio.h)
int sum=0,t=1;
for(int n=1;n<8;n++)
{
for(int i;i<=n;i++)
{
t=t*2
}
t=1;
sum=sum+t
}
printf("2+4+……+128=%d",sum);
int main()
{
int i = 2;
int s =0 ;
for(i=2; i <= 128; i = i*2)
{
s += i;
}
printf(" s = %d\n" , s);
return 0;
}
int main(){ int i = 2; int s =0 ; for(i=2; i <= 128; i = i*2) s =s+ i; printf(" s = %d\n" , s); return 0;}