2015-11-05 45 views
-5

我是新來的,我希望你能幫我完成我爲編程課所做的任務。任務是創建一個氣候控制器,如果溫度> 22.2°,則應該冷卻房間,如果溫度介於兩者之間,則溫度會升高,如果溫度介於兩者之間則什麼都不做。 我做的代碼是:C錯誤:控制到達非空函數結束

/* 
Compile: make climate_control1 
Run: ./climate_control1 
*/ 

#include "base.h" 

/* 
Eine Klimaanlage soll bei Temperaturen unter 18.5 °C heizen, bei 18.5-22.2 °C nichts tun und bei Temperaturen ab 22.2 °C kühlen. 
Entwickeln Sie eine Funktion zur Regelung der Klimaanlage, die abhängig von der Temperatur heizt, ausschaltet oder kühlt. 
*/ 

enum TemperatureStage { 
    LOW_TEMPERATURE, 
    HIGH_TEMPERATURE 
}; 

typedef int Degree; // int represents temperature in degree celsius 

const Degree LOW_TEMPERATURE_BOUNDARY = 18.5; // interpret.: Temperature in degree celsius. 
const Degree HIGH_TEMPERATURE_BOUNDARY = 22.2; // interpret.: Temperature in degree celsius. 

//Degree -> Degree. 

Degree climate_control(Degree degree); 


void climate_control_test() { 
    check_expect_i(climate_control(LOW_TEMPERATURE_BOUNDARY),0); 
    check_expect_i(climate_control(HIGH_TEMPERATURE_BOUNDARY), 0); 
    check_expect_i(climate_control(10), LOW_TEMPERATURE_BOUNDARY); 
    check_expect_i(climate_control(20.6), 0); 
    check_expect_i(climate_control(33), HIGH_TEMPERATURE_BOUNDARY); 

} 

// regulate the temperature. 

Degree climate_control(Degree degree) { 
    if (degree == LOW_TEMPERATURE_BOUNDARY) { 
     return 0; 
    } else if (degree < LOW_TEMPERATURE_BOUNDARY) { 
    return LOW_TEMPERATURE_BOUNDARY; } 
    else if (degree == HIGH_TEMPERATURE_BOUNDARY) { 
     return 0; 
    } else if (degree > HIGH_TEMPERATURE_BOUNDARY) { 
    return HIGH_TEMPERATURE_BOUNDARY; } 
} 




int main (void) { 
    climate_control_test(); 
    return 0; 
} 

錯誤「控制到達非void函數結束」似乎每次我嘗試編譯時間。我不知道它有什麼問題。我需要說的是,在我三週前開始學習之前,我幾乎沒有編碼經驗。

+7

這顯然不是C#...你應該知道你在用什麼語言 – Matyas

+1

Degree degree_control(Degree degree)''應該有一個簡單的'else'語句,以避免if語句被碰到是發生了什麼)。編譯器不會評估你的代碼路徑,它只是知道你的'if'語句有可能落空,到達該函數的結尾而不返回任何東西。 –

回答

1

這是因爲你的函數有一個可能的代碼路徑,讓if在沒有返回任何東西的情況下崩潰。從技術上講,這不應該是可能的,但編譯器已經注意到了這種可能性,並且不會讓你繼續。你的功能應該看起來更像這樣:

Degree climate_control(Degree degree) { 
    if (degree == LOW_TEMPERATURE_BOUNDARY) { 
     return 0; 
    } else if (degree < LOW_TEMPERATURE_BOUNDARY) { 
    return LOW_TEMPERATURE_BOUNDARY; } 
    else if (degree == HIGH_TEMPERATURE_BOUNDARY) { 
     return 0; 
    } else if (degree > HIGH_TEMPERATURE_BOUNDARY) { 
    return HIGH_TEMPERATURE_BOUNDARY; } 

    return 0; 
} 

爲什麼編譯器會這麼想?會發生什麼上面的代碼,如果一些腦死亡(或醉酒)程序員這樣做:

const Degree LOW_TEMPERATURE_BOUNDARY = 18.5; 
const Degree HIGH_TEMPERATURE_BOUNDARY = -22.2; //Notice the sign change? 

現在你climate_control功能都將落空。

+0

非常感謝! :) – Inkognito

相關問題