c - 在C中将信息存储到变量中的问题

标签 c variables storage scanf

我编写了以下代码来介绍 C 类。但是由于某种原因我无法弄清楚为什么 scanf不会将输入存储到华氏变量中,因此不允许我正确进行计算。我将起始值从 0 更改为 212,以确保我的计算正确,但它仍然不允许我更新。

 #include <stdio.h>
 int main(void){

 double fahrenheit = 212.00;
 double celcius = 0;

 //prompt the user for the information                                                 
 printf("Enter a temperature in degrees Fahrenheit >");

 //store the information in the Fahrenheit var.                                        
 scanf("%f", &fahrenheit);
 //calculate the change in metrics                                                     
 celcius = (fahrenheit-32)*.5556 ;
 printf("%f degrees Fahrenheit is equal to %f degrees       celcius\n",fahrenheit,celcius);
}

最佳答案

double 参数一起使用的正确 printfscanf 格式是 %lf。不是%f,而是%lf。不要将 %fdouble 一起使用。应该是

scanf("%lf", &fahrenheit);
...
printf("%lf degrees Fahrenheit is equal to %lf degrees celcius\n",
  fahrenheit, celcius);

请注意,%f 将与 printf 中的 double 一起使用(不在 scanf 中),但使用它这种方式仍然是一个坏习惯,这只会让初学者产生这样的误解:printfscanf 在这方面某种程度上“不一致”。

格式说明符和参数类型之间的匹配定义明确,并且在 printfscanf 之间保持一致:

  • %f 代表 float
  • %lf 代表 double
  • %Lf 代表 long double

关于c - 在C中将信息存储到变量中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28222161/

相关文章:

variables - 使用 SASS 将字符串和变量合并到一个变量

Cassandra READ Where In 性能

c++ - MATLAB 在执行半色调 mex 包装函数时崩溃?

c - 将二维数组传递给线程函数

javascript - 在 Javascript 中访问变量名中的计数器(内部代码)

jquery - 将变量传递给 jqPlot 图表

linux - 从 Centos 6.7 升级到 7 而不会损害 LVM 中的数据

python - 为什么 Jupyter 无法读取文件夹中的 csv 文件?

c - 使用 rtld/free loader/linkers 加载加密的共享对象

c++ - 在 C++ 中使用 C 库