关于#c语言#的问题,请各位专家解答!

一球从h米的高度自由落下,每次落地后又反跳回原高度的一半,再落下。求它在第n次落地时,共经过多少米,第n次反弹多高。

输入格式:
输入在一行中给出两个非负整数,分别是皮球的初始高度h和n。

输出格式:
在一行中顺序输出皮球第n次落地时在空中经过的距离、以及第n次反弹的高度,其间以一个空格分隔,保留一位小数。

输入样例:
33 5
输出样例:
94.9 1.0


```c
#include 

int main() {
    double height, total_distance, bounce_height;
    int n;

    scanf("%lf%d", &height, &n);

    // 计算总共经过的距离
    total_distance = height;
    for (int i = 1; i < n; i++) {
        bounce_height = height / 2;  // 每次反弹的高度
        total_distance += height + bounce_height;  // 累加每次落地和反弹的距离
        height = bounce_height;  // 更新下一次落地的高度
    }
    total_distance += height * 2;  // 加上最后一次落地的距离

    printf("%.1f %.1f\n",total_distance,bounce_height);

    return 0;
}

只有部分答案正确,程序运行后不能完全正确,但是检查好几遍都没有发现逻辑问题

代码如下

#include <stdio.h>
 
int main() {
    double height, total_distance, bounce_height;
    int n;
 
    scanf("%lf%d", &height, &n);
 
    // 计算总共经过的距离
    for (int i = 1; i < n; i++) {
        bounce_height = height / 2;  // 每次反弹的高度
        total_distance += height + bounce_height;  // 累加每次落地和反弹的距离
        height = bounce_height;  // 更新下一次落地的高度
    }
    total_distance += height;  // 加上最后一次落地的距离
    bounce_height = height / 2;
    printf("%.1f %.1f\n",total_distance,bounce_height);
 
    return 0;
}
 

语法没错逻辑有问题!下面仅供参考。

img

img

#include <stdio.h>
int main()
{
    double height, total_distance = 0.0, bounce_height = 0.0;
    int n;
    scanf("%lf%d", &height, &n);

    total_distance += height;

    for (int i = 1; i <= n; i++)
    {
        /* 第x次落地经过多少米 */
        total_distance += bounce_height * 2;

        bounce_height = height / 2;
        // 每次反弹的高度 

        height = bounce_height;
        // 更新下一次落地的高度
    }

    printf("%.1lf %.1lf\n", total_distance, bounce_height);
    return 0;
}