【问题标题】:Trouble with temperature converter using readline function in C在 C 中使用 readline 函数的温度转换器出现问题
【发布时间】:2020-09-04 21:15:20
【问题描述】:

所以我正在尝试做一个从摄氏到华氏的温度转换器,由于某种原因,我的代码的输出全部被破坏了。这是我的代码:

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

int main(void) 
{
  char *temperature = readline("Enter a temperature in celsius: ");

  double t1 = ((double)*temperature);
  double t2 = ((double)*temperature * 1.8) + 32;
  printf("%f° in Celsius is equivalent to %f° Fahrenheit.", t1, t2);
  return 0;
}

输出:

Enter a temperature in celsius: 100
49.000000° in Celsius is equivalent to 120.200000° Fahrenheit.

谁能告诉我我的代码有什么问题?

【问题讨论】:

  • 您正试图通过类型转换将字符串转换为双精度。那是行不通的。考虑使用sscanf 之类的strtod 将字符串转换为双精度。

标签: c readline temperature


【解决方案1】:

在调用readline 之后,temperature 包含一个指向缓冲区的指针,该缓冲区包含用户输入的字符串。然后当你这样做时:

(double)*temperature

您正在获取字符串中第一个字符的字符代码并将其转换为类型double。例如,如果输入是“100”。那么第一个字符就是字符'1',它的ASCII码是49。这就是你得到你所看到的值的原因。

您需要使用strtod 函数将数字的字符串表示形式转换为double

double t1 = strtod(temperature, NULL);
double t2 = (t1 * 1.8) + 32;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多