【问题标题】:C++: Trouble with a nested if loop not ending properlyC++:嵌套 if 循环没有正确结束的问题
【发布时间】:2012-03-17 14:17:09
【问题描述】:

堆栈溢出。我是 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?

【问题讨论】:

  • 强烈建议:单步调试器下的代码,看看“高度”和“距离”是如何随着循环迭代而变化的。我想你很快就会发现问题;)
  • distance = ((0.5 * acceleration) * (time * time)); 始终计算为 0since time=0
  • 如果您希望程序不打印负数,请将您的条件(if 语句)移到 printf() 之前。
  • @Als time 在循环中是递增的,所以在第一次迭代后它变为非零。

标签: c loops for-loop while-loop


【解决方案1】:

打印前改变海拔高度。

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

【讨论】:

  • 非常感谢,既然你指出了这一点,我感到非常愚蠢。
【解决方案2】:

导致这种情况的问题是您的采样间隔:您以一秒为增量进行,因此您的程序计算下降到负高度。你应该稍微改变你的代码:

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

}

这不会打印物体撞击地面的时间。您应该在循环之后执行此计算,使用剩余的高度、速度 (acceleration*time) 和 acceleration,并求解剩余时间的方程,得到代表秒的分数。

【讨论】:

    【解决方案3】:

    您在设置为 0 之前打印出高度。由于您的公式假设时间以 1 秒为间隔发生,因此打印出的是当时的高度。因此,如果您从 20 英尺处掉下一个物体,1 秒后它会在 4 英尺处,而 2 秒后它会在 -60 英尺处——它撞击地面的时间实际上是 1.25 秒。

    【讨论】:

      猜你喜欢
      • 2017-11-01
      • 2017-06-04
      • 1970-01-01
      • 2019-05-05
      • 2015-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多