c语言程序pta高空坠球
时间: 2024-01-15 10:19:38 浏览: 112
使用C语言写一个程序,小球自由落体
以下是两种C语言程序实现高空坠球的例子:
1. 使用for循环计算高空坠球的距离和反弹高度:
```c
#include <stdio.h>
int main(void) {
int n, i;
float height, sum, item; //item是结果
printf("此程序是计算高空坠球高度,\n");
printf("请输入高度,\n高度(米)=");
scanf("%f", &height);
sum = height; //给设置sum初始值
printf("其中n代表落地次数,请输入n的数值,\nn=");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
item = height * 1 / 2;
if (i == n) //如果循环次数和落地次数相同,不继续累加sum值
break;
sum = sum + item * 2;
height = item; //将结果赋值给高度,重置高度值
}
printf("第%d次落地时,在空中一共经过%.1f米,第%d反弹时高度时%.1f米", n, sum, n, item);
return 0;
}
```
2. 一行中顺序输出皮球第n次落地时在空中经过的距离和第n次反弹的高度:
```c
#include<stdio.h>
int main() {
double height;
double midheight, sumheight = 0;
int n;
scanf("%lf %d", &height, &n);
if (n == 0) { //满足测试点n=0时要求
midheight = 0;
sumheight = 0;
} else {
for (int i = 0; i < n; i++) { //循环计算n次反弹的高度
midheight = height / 2;
sumheight = sumheight + midheight + height;
height /= 2.0;
}
sumheight -= height;
}
printf("%.1f %.1f", sumheight, midheight);
return 0;
}
```
阅读全文