c - 在 C 中,尝试使用将华氏度转换为开尔文的程序

标签 c

<分区>

但是当我运行它并插入任何随机数时,计算不起作用或发生变化...需要一些指导。我是 C 和一般编程的新手,所以请提供易于理解的帮助。

 #include <stdio.h>
double const change_celcius = 32.0;
double const change_kelvin = 273.15;

void temperatures(double n);

int main(void)
{
    int q = 'q';
    double user_number;

    printf("Enter the fahrenheit: \n");
    scanf("%f", &user_number);

    while (user_number != q)
    {
        temperatures(user_number);
        printf("\n");
        printf("Enter the fahrenheit: \n");
        scanf("%f", &user_number);
    }
}

void temperatures(double n)
{
    double celsius, kelvin;

    celsius = 5.0 / 9.0 * (n - change_celcius);
    kelvin = 5.0 / 9.0 * (n - change_celcius) + change_kelvin;

    printf("fahrenheit: %.2f - celsius is: %.2f - kelvin is: %.2f", 
            n, celsius, kelvin);

}

最佳答案

我不相信所有的 use %lf instead of %f 评论本身都能修复你的程序。 q(表示“退出”)的处理也有问题,所以让我们也解决这个问题。首先,我们将使用 POSIX 函数 getline()将其读入字符串并测试它是否为“q”。如果不是,我们将 sscanf 将其转换为 double 值并将其用作我们的温度:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

double const change_celsius = 32.0;
double const change_kelvin = 273.15;

void temperatures(double n)
{
    double celsius = 5.0 / 9.0 * (n - change_celsius);
    double kelvin = 5.0 / 9.0 * (n - change_celsius) + change_kelvin;

    printf("fahrenheit: %.2f - celsius is: %.2f - kelvin is: %.2f\n", n, celsius, kelvin);
}

int main(void)
{
    char *user_string = NULL;
    ssize_t user_string_length;
    size_t user_string_capacity = 0;

    while (1)
    {
        printf("Enter the fahrenheit: ");

        if ((user_string_length = getline(&user_string, &user_string_capacity, stdin)) < 1)
            break;

        if (strncmp(user_string, "q\n", (size_t) user_string_length) == 0)
            break;

        double user_number;

        if (sscanf(user_string, "%lf", &user_number) == 1)
            temperatures(user_number);
    }

    if (user_string != NULL)
        free(user_string); // free memory allocated by getline()

    if (user_string_length == -1)
        putchar('\n'); // output courtesy newline if user used ^D to exit

    return(0);
}

我们检查 sscanf 的返回值,这样错误的输入就不会导致程序使用上次正确的输入重新计算。相反,它只会再次提示输入。

关于c - 在 C 中,尝试使用将华氏度转换为开尔文的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39194227/

相关文章:

c++ - 如果我删除其他进程的共享内存会怎样?

C:对于这个要求,有没有比 FIFO 队列实现更好的东西?

c - 将变量从终端传递到 makefile

c - 我们什么时候应该使用链表而不是数组,反之亦然?

C - 从不同的函数访问结构变量

c++ - '.' 和 '->' 在数组中使用时有什么区别?

c - 仅通过 EOF 结束 while 循环一次

c - BSD C Bind() 到 UDP 挂起的套接字

c++ - 顺序内存分配

C Linux 共享内存错误 - ftruncate