我编写了以下代码来介绍 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
参数一起使用的正确 printf
和 scanf
格式是 %lf
。不是%f
,而是%lf
。不要将 %f
与 double
一起使用。应该是
scanf("%lf", &fahrenheit);
...
printf("%lf degrees Fahrenheit is equal to %lf degrees celcius\n",
fahrenheit, celcius);
请注意,%f
将与 printf
中的 double
一起使用(不在 scanf
中),但使用它这种方式仍然是一个坏习惯,这只会让初学者产生这样的误解:printf
和 scanf
在这方面某种程度上“不一致”。
格式说明符和参数类型之间的匹配定义明确,并且在 printf
和 scanf
之间保持一致:
%f
代表float
%lf
代表double
%Lf
代表long double
。
关于c - 在C中将信息存储到变量中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28222161/