C中void和float函数的区别

Alb*_*ert 4 c function

我正在学习 Udemy C 课程,并且对 C 中的函数产生了一些疑问。其中一个练习是关于使用函数进行温度转换(摄氏度、F 和 K)的,当时我的第一个想法是:

void CF(){
    float temp1, temp2;

    printf("Escribe que temperatura quieres convertir a Fahrenheit: ");
    scanf("%f", &temp1);

    temp2 = (temp1 * 1.8) + 32;

    printf("La temperatura en Fahrenheit es: %f", temp2);
}
Run Code Online (Sandbox Code Playgroud)

但是解决的练习使用:

float fahrenheit(float C){
    float F=0;
    F = (9*C)/5 + 32;
    return F;
}
Run Code Online (Sandbox Code Playgroud)

并通过“int main”程序输入数据,同时我通过函数进行介绍。

我的问题是: - 最好通过 int 主代码或函数引入数据?- 为什么他使用“Float”函数而我使用“void”函数并且在两种情况下都能正常工作?

无论如何,我的代码有效,但我想知道什么更好以及为什么。

预先感谢并原谅我的英语。

Oli*_*son 10

The purpose of a function is to encapsulate a frequently used calculation. If you code it as returning a value, then you can call it whenever you want inside a bigger program, regardless of whether you want to print out the result or not. Thus the second function is more reusable.

While there is nothing wrong with the way you wrote the function, it assumes that you sit by a keyboard to enter a value, and that you will just want to look at the conversion result.

现在假设您编写了一个工具,它获取以摄氏度为单位的温度列表(来自电子表格),并希望将它们全部转换为华氏度。您的函数在这里不起作用,但第二个版本可以与它周围的包装器一起使用,以从电子表格中读取摄氏度值,调用该函数,然后将转换后的值放在其他地方。

一般来说,将函数的功能性保持在最低限度是一个很好的设计原则,以便它可以在更多不同的情况下使用。