2017-02-10 83 views
0

這是我寫的。我猜這可能是我的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; 
} 
+0

它在程序中停止的地方.....它甚至會進入while循環嗎?添加一些其他打印語句並以這種方式進行調試 –

+0

'printf(「\ n%1.0lf \ t \ t \ t%.1lf」,count,area_uncut);''使用' %lf',這是未定義的行爲(更改爲'%d')。 –

+6

'while(count <= years);''''''創建一個空的循環體。在你的編譯器中打開完整的警告,它應該警告這個。 – Barmar

回答

4

有這行的最後一個額外的;while (count <= 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格式也不正確。絕對編譯時啓用更多警告。

相關問題