初学者求教一道c语言题目
皮球在第n次反弹落地时,在空中经过的路程是多少米?第n次反弹的高度是多少?(输出保留1位小数)
我的答案:#include<stdio.h>
#include<math.h>
int main(void)
{
int height,n,i,j,item;
double distance;
printf("Input height: ");
scanf("%d",&height);
printf("Input n: ");
scanf("%d",&n);
distance=0;
for(i=1;i<=n;i++){
item=1;
for(j=1;j<=i;j++)
item=item*2*height*pow(0.5,j);
distance=distance+height+item;
}
height=height*pow(0.5,n);
printf("distance=%.1f\n",distance);
printf("height=%.1f",height);
return 0;
}
求教怎么改?我快要崩溃了~~ 展开
#include<stdio.h>
#include<math.h>
int main(void)
{
int n,i;
double distance;
double height;//高度应该是double类型
printf("Input height: ");
scanf("%lf",&height);//高度应该是double类型
printf("Input n: ");
scanf("%d",&n);
distance=0;
distance+=height;//加上最开始的高度,
for(i=1;i<=n;i++){
//item=1;
//for(j=1;j<=i;j++)
//item=item*2*height*pow(0.5,j);
distance+=height*pow(0.5,i)*2;
}
height=height*pow(0.5,n);
//小数点后多保留几位,不然容易出现0.0,同时double类型应该是%lf
printf("distance=%.6lf\n",distance);//printf("distance=%.1f\n",distance);
printf("height=%.6lf\n",height);//printf("height=%.1f",height);
return 0;
}
结果:
恩,谢谢了。我现在刚学c语言的嵌套循环,有点迷茫。能向你请教一下什么情况下该使用嵌套循环吗?
多于两个变量需要依次改变时,
#include<stdio.h>
int main(void)
{
int i,n;
double distance,height;
printf("Input height:");
scanf("%lf",&height);
printf("Input n:");
scanf("%d",&n);
distance = height; //第一次落地的距离
for(i=1;i<n;i++)
{
height /= 2.0; //每次弹起都是上次的一半
distance +=(height * 2); //每次落地都是弹起的高度*2
}
height /= 2.0; //第N次落后再弹起一次
printf("The distance %lf,\n",distance);
printf(" the times %dth.\n",n);
printf("The height %lf\n",height);
return 0;
}
Input height:10
Input n:2
The distance 20.000000,
the times 2th.
The height 2.500000