• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

为CS50实验1学习C:人口增长-我的程序可以运行,但没有达到我的预期

用户头像
it1352
帮助1

问题说明

我的程序正在运行,但实际上并没有执行我想要的程序.它提示输入开始大小,然后提示输入结束大小,仅此而已.我希望它然后使用输入的数字来计算需要多少年,但我似乎无法让它做到这一点.预先感谢您的任何建议!

My program runs, but does not actually do what I want it to do. It prompts for start size, then prompts for end size, and then that's it. I want it to then use the inputted numbers to calculate how many years it would take but I can't seem to get it to do that. Thanks in advance for any suggestions!

我的代码如下:

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    // TO DO: Prompt for start size
    int start;
    do
    {
        start = get_int("Start Size: ");
    }
    while (start < 9);

    // TO DO: Prompt for end size
    int end;
    do
    {
        end = get_int("End Size: ");
    }
    while (end <= start);

    // TO DO: Calculate number of years until we reach threshold
    int years;
    do
    {
        years = (start   start/3 - start/4);
    }
    while (end > start);

    // TO DO: Print number of years
    printf("Years:%i\n", years);
}

正确答案

#1

按照@kaylum的建议,如果要使用调试器逐步执行程序,您将很容易发现程序出了什么问题.

As @kaylum suggests, you would easily see what's wrong with your program if you were to step through it, using a debugger.

以下是有关在Linux和Windows上进行调试的两个Stackoverflow问题:

Here are two Stackoverflow questions about debugging on Linux and on Windows:

尽管我猜您的课程人员建议了一些开发环境,该开发环境本身允许进行调试,但可能与这些问题中的建议有所不同.

although I am guessing your course staff has suggested some development environment which itself allows for debugging, possibly a bit differently than the suggestions in those questions.

如果要调试程序,逐步执行单个命令,您会注意到执行会不断迭代 do ... while(end> start); 循环,如@UnholySheep所述.然后您会想到等等,为什么它不退出循环?"并且您会注意到,您只更改了 years 的值,而循环退出条件关于 end start 却没有改变.

If you were to debug the program, stepping through individual commands, you would notice that execution keeps iterating the do ... while (end > start); loop, as @UnholySheep notes. Then you would think "wait, why isn't it exiting the loop?" and you would notice that you only change the years value, while your loop exit condition regardings end and start, which don't change.

并且,作为将来的参考-大多数StackOverflow用户都希望提问者进行尽职调查",并在寻求解决方案之前做出合理的努力以找出他们的问题.现在您已经了解了调试器-请在询问为什么我的程序为什么没有达到我的期望"之前使用一个调试器.

Also, and for future reference - most StackOverflow users expect question askers to perform their "due diligence", making reasonable efforts to figure out their problems before asking us for a solution. Now that you know about debuggers - please use one before asking "Why does my program not do what I expected".

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcgbhhe
系列文章
更多 icon
同类精品
更多 icon
继续加载