【问题标题】:Why do I keep getting an empty table when I run this program?为什么我运行这个程序时总是得到一个空表?
【发布时间】:2017-02-10 00:09:30
【问题描述】:

这是我写的。我猜这可能与我的while 循环的逻辑有关,但我无法完全发现它!任何帮助表示赞赏!谢谢。

#include <stdio.h>
#include <math.h>

//Open main function.
int main(void)
{
    double new_area, area_total = 14000, area_uncut = 2500, rate = 0.02, years;
    int count = 0;

    printf("This program is written for a plot of land totaling 14000 acres,    "
           "with 2500 acres of uncut forest\nand a reforestation rate "
           "of 0.02. Given a time period (years) this program will output a table\n"
           "displaying the number acres reforested at the end of "
           "each year.\n\n\n");

    printf("Please enter a value of 'years' to be used for the table.\n"
           "Values presented will represent the number acres reforested at the end of "
           "each year:>> ");

    scanf("%lf", &years);

    years = ceil(years);

    printf("\n\nNumber of Years\t\tReforested Area");

    while (count <= years);
    {
        count = count + 1;
        new_area = area_uncut + (rate * area_uncut);
        printf("\n%1.0lf\t\t\t%.1lf", count, area_uncut);
        area_uncut += new_area;
    }

    return 0;
}

【问题讨论】:

  • while (count &lt;= years); -- 那里的; 创建了一个空循环体。在您的编译器中打开完整警告,它应该对此发出警告。
  • @KeineLust 这就是为什么它是一个警告,而不是一个错误。这是一个常见的错字,编译器会发出警告,以防它不是您真正的意思。
  • 你启用什么标志来接收这样的警告?
  • @Barmar:我用g++-Wall 编译,但它没有出现。我仍然赞成您的评论,因为删除该分号可以解决 OPs 问题。当我尝试使用gcc 编译时,由于ceil 而出现错误。
  • gcc 在 Linux 上忽略了这个标志 :(

标签: c loops while-loop


【解决方案1】:

在这一行的末尾多了一个;while (count &lt;= years);

它被解析为 while 循环的空主体,导致它永远迭代,因为 count 根本没有更新。

这里有一种方法可以避免这种愚蠢的错误:使用 Kernighan 和 Ritchie 样式,其中 { 位于行尾,开始控制块:

while (count <= years) {
    count = count + 1;
    new_area = area_uncut + (rate * area_uncut);
    printf("\n%d\t\t\t%.1f", count, area_uncut);
    area_uncut += new_area;
}

使用这种样式,额外的; 不太可能被输入,并且更容易被发现不协调。

还要注意count 被定义为int,所以printf 的格式也不正确。肯定编译时启用更多警告。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-23
    • 2023-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 2016-07-08
    • 1970-01-01
    相关资源
    最近更新 更多