所以我试图做一个从摄氏度到华氏度的温度转换器,但由于某种原因,我的代码的输出都被打乱了。这是我的代码:
#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.
有人能告诉我我的代码出了什么问题吗?
调用readline
后,temperature
包含一个指向缓冲区的指针,该缓冲区包含用户输入的字符串。然后当你这样做时:
(double)*temperature
您将获取字符串中第一个字符的字符代码,并将其转换为类型double
。因此例如如果输入是"0";100〃;。那么第一个字符是字符'1'
,其ASCII码是49。这就是为什么你会得到你所看到的价值。
您需要使用strtod
函数,该函数将数字的字符串表示转换为double
:
double t1 = strtod(temperature, NULL);
double t2 = (t1 * 1.8) + 32;