2015-11-05 31 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

相关问题