gpt4 book ai didi

C++ : Trouble with a nested if loop not ending properly

转载 作者:太空宇宙 更新时间:2023-11-04 03:02:42 25 4
gpt4 key购买 nike

计算器。我是 C++ 的新手,我的作业有最后一个问题。我正在尝试编写一个程序来计算物体从基准高度下落的速度,并将该信息显示为物体的高度与其下落的时间量(以秒为单位)的关系。这是我到目前为止的代码:

#include <stdio.h>

int main() {

int acceleration, altitude, time;
double distance;

acceleration = 32;
time = 0;

printf("What is the altitude you are dropping your object from?\n");
scanf("%d", &altitude);

printf("Time Altitude\n");

while (altitude > 0){
distance = ((0.5 * acceleration) * (time * time));
altitude = altitude - distance;
printf("%d %d\n", time, altitude);
time++;
if (altitude <= 0){
altitude = 0;
}
}

return 0;
}

我知道距离方程式略有偏差,但目前我更关心的是,当物体撞击地面时,程序不会打印出高度为 0。相反,它会打印出 -104,并且由于无法实现负距离,所以我想解决这个问题。

所以我的问题是:我的 while 循环/嵌套 if 循环有什么问题导致程序为表中的最后一个条目打印出 0?

最佳答案

打印前改变高度。

while (altitude > 0){
distance = ((0.5 * acceleration) * (time * time));
altitude = altitude - distance;
if (altitude <= 0){
altitude = 0;
}
printf("%d %d\n", time, altitude);
time++;
}

关于C++ : Trouble with a nested if loop not ending properly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9476357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com